如何在JavaScript中整齐地格式化递归控制台日志Json对象?



我递归列出了一个嵌套的json对象。当我控制日志时,我以一种很难知道一组对象从哪里开始或结束的方式获取数据。

如何格式化响应?

const obj = {
fullName: 'Ram Kumar',
age: 31,
gender: male
}
},
fullName: 'Ranbir Singh',
age: 22,
gender: male
}
},
function printAllVals(obj) {
for (let prop in obj) {
if (typeof obj[prop] === "object") {
printAllVals(obj[prop])
} else {
console.log(prop + ':' + obj[prop]);
}
}
}

我得到了:

fullName:Ram Kumar
age: 31
gender: male
fullName:Ranbir Singh
age: 22
gender: male

我想要的是这样的东西。为了清晰或易于理解而格式化或分离对象的任何内容:

fullName:Ram Kumar
age: 31
gender: male 
---
fullName:Ranbir Singh
age: 22
gender: male

您的对象看起来不合法,所以我添加了"child"子键向下迭代到。

在调用递归函数调用之前,打印一个行分隔符。

const printAllVals = (obj) => {
for (let prop in obj) {
if (typeof obj[prop] === 'object') {
console.log('---');                  // Print line, before the child.
printAllVals(obj[prop])
} else {
console.log(`${prop}: ${obj[prop]}`);
}
}
}
const obj = {
fullName: 'Ram Kumar',
age: 31,
gender: 'male',
child: {                                // sub-key?
fullName: 'Ranbir Singh',
age: 22,
gender: 'male'
}
};
printAllVals(obj);
.as-console-wrapper { top: 0; max-height: 100% !important; }

最新更新