gpt4 book ai didi

javascript - 打印任何 javascript 对象

转载 作者:行者123 更新时间:2023-11-30 19:54:54 25 4
gpt4 key购买 nike

我不是新手程序员,我知道如何使用 console.log(myObject)。我想要的是能够将任何对象打印到具有最大深度的字符串,并且其中没有空属性。有很多次我需要将一个对象打印到控制台或某个地方的日志中,它会打印整个对象。这可能会占用太多空间,我的终端无法容纳整个对象。我在这里问这个问题的原因是有人可以识别我可能遗漏的所有边缘情况或我想得太多的地方。

这是一个例子:

[
{
a: 'a',
b: '',
c: {
d: 'd',
e: {
f: {
g: 'g'
}
},
h: [
'i',
'j',
{ k: 'k' }
],
l: [],
}
}
]

printAny(myObject,5) 应该输出:

[
{
a: 'a',
c: {
d: 'd',
e: {
f: '<objec>'
},
h: [
'i',
'j',
'<object>'
],
}
}
]

我为更多示例制作了一个 jsbin:https://jsbin.com/buzugipole/edit?js,console

它还应该处理循环。我不反对使用 npm 库,这就是我现在正在使用的,但它是 3 个不同库的大杂烩,它们都试图解决这个问题。

最佳答案

您可以通过递归迭代对象的键和值来克隆对象,并传递 nestingToGo决定在 <object> 之前允许嵌套多少的数字打印而不是实际对象:

const obj = [
{
a: 'a',
b: '',
c: {
d: 'd',
e: {
f: {
g: 'g'
}
},
h: [
'i',
'j',
{ k: 'k' }
],
l: [],
}
}
];

function replaceNested(obj, nestingToGo) {
const initial = Array.isArray(obj) ? [] : {};
return Object.entries(obj).reduce(( a, [key, val]) => {
if (typeof val === 'object') {
a[key] = nestingToGo === 0
? '<object>'
: replaceNested(val, nestingToGo - 1)
} else {
a[key] = val;
}
return a;
}, initial);
}

function printAny(obj, maxNesting) {
const slimmerObj = replaceNested(obj, maxNesting);
console.log(JSON.stringify(slimmerObj, null, 2));
}
printAny(obj, 3);

另一种选择是使用正则表达式替换所有以足够空格开头的行:

const obj = [
{
a: 'a',
b: '',
c: {
d: 'd',
e: {
f: {
g: 'g'
}
},
h: [
'i',
'j',
{ k: 'k' }
],
l: [],
}
}
];

function printAny(obj, maxNesting) {
const stringified = JSON.stringify(obj, null, 2);
const maxSpaces = maxNesting * 2;
const pattern = new RegExp(
String.raw`[{\[]\n {${maxSpaces + 2}}\S[\s\S]+?^ {${maxSpaces}}\S`,
'gm'
);
const slimStringified = stringified.replace(pattern, '<object>');
console.log(slimStringified);
}
printAny(obj, 4);

错误不能很好地序列化,但如果您必须,您可以给出 Error.prototype定制toJSON方法:

const obj = [
{
err: new Error('foo'),
a: 'a',
b: '',
c: {
d: 'd',
e: {
f: {
g: 'g'
}
},
h: [
'i',
'j',
{ k: 'k' }
],
l: [],
}
}
];

Error.prototype.toJSON = function() {
return '<Error> ' + this.message;
};
function printAny(obj, maxNesting) {
const stringified = JSON.stringify(obj, null, 2);
const maxSpaces = maxNesting * 2;
const pattern = new RegExp(
String.raw`[{\[]\n {${maxSpaces + 2}}\S[\s\S]+?^ {${maxSpaces}}\S`,
'gm'
);
const slimStringified = stringified.replace(pattern, '<object>');
console.log(slimStringified);
}
printAny(obj, 4);

关于javascript - 打印任何 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com