漂亮的打印对象
将对象或数组转换为格式化的字符串
这是重写 字符串对象 在 Typescript中,修改为内含依赖性,使其能与框外的ES5相容.
当您想要以格式化的方式获得对象的字符串表示时有用 .
它还处理循环引用,并让您指定引用类型.
安装
$ npm install @base2/pretty-print-object
使用量
import { prettyPrint } from '@base2/pretty-print-object';
const obj = {
foo: 'bar',
arr: [1, 2, 3],
nested: {
hello: 'world'
}
};
const pretty = prettyPrint(obj, {
indent: ' ',
singleQuotes: false
});
console.log(pretty);
/*
{
foo: "bar",
arr: [
1,
2,
3
],
nested: {
hello: "world"
}
}
*/
API 密码
prettyPrint( 输入, [选项])
无效的日期打印为 Invalid Date 而不是放弃一个例外。 有效日期 保留 new Date('...') 代表权.
通知参考资料将替换为 "[Circular]"。 。 。 .
仅在必要时引用对象密钥,例如:, {'foo-bar': true}。 。 。 .
投入
类型 : Object Array
选项
类型 : Object
缩进
类型 : string
默认 : \t
偏好缩入.
单引号
类型 : boolean
默认 : true
设定为假以获得双引字符串 .
过滤器( obj, 道具)
类型 : Function
预期返回a boolean 是否包括财产 prop 对象 obj 在输出中.
变换( obj、 道具、 原始结果)
类型 : Function
默认 : undefined
预期返回a string 转换由字符串产生的字符串 obj[prop]。这可用于检测需要以特定方式被字符串的特殊类型物体。 这个 transform 函数在此情况下可能返回一个替代字符串,否则返回 originalResult。 。 。 .
这里有一个例子,使用 transform 选项以遮盖名为“密码”的字段:
import { prettyPrint } from '@base2/pretty-print-object';
const obj = {
user: 'becky',
password: 'secret'
};
const pretty = prettyPrint(obj, {
transform: (obj, prop, originalResult) => {
if (prop === 'password') {
return originalResult.replace(/\w/g, '*');
}
return originalResult;
}
});
console.log(pretty);
/*
{
user: 'becky',
password: '******'
}
*/
内置切开器Limit
类型 : number
设置时, 将内入值至 inlineCharacterLimit 长度,以便输出更多点.
例如,在README顶端的例子:
import { prettyPrint } from '@base2/pretty-print-object';
const obj = {
foo: 'bar',
arr: [1, 2, 3],
nested: {
hello: 'world'
}
};
const pretty = prettyPrint(obj, {
indent: ' ',
singleQuotes: false,
inlineCharacterLimit: 12
});
console.log(pretty);
/*
{
foo: "bar",
arr: [1, 2, 3],
nested: {
hello: "world"
}
}
*/
如你所见, arr 被打印为一行,因为它的字符串短于12个字符.