gpt4 book ai didi

javascript - 在下一行(新行)中显示嵌套对象属性

转载 作者:行者123 更新时间:2023-12-03 08:23:12 24 4
gpt4 key购买 nike

我有对象数组,其中有子对象(嵌套对象)。整个结构看起来与此类似(所有子对象都有相同的标签,只有值不同):

           var arr = [
obj0 = {

subObj0: {
name: "John",
lastName: "Doe",
age: 50,
nick: "JD",
phone: 123456
},
subObj1: {
name: "Jane",
lastName: "Dee",
age: 30,
nick: "lady",
phone: 654098
},
subObj2: {
name: "Ash",
lastName: "Bash",
age: 33,
nick: "asdB",
phone: 987123
}
},
obj1 = {
subObj0: {
name: "Asd",
lastName: "Dsa",
age: 10,
nick: "none",
phone: 12
},
subObj1: {
name: "Ivy",
lastName: "Mash",
age: 3,
nick: "IvMash",
phone: 9823
}

}

];

我试图在控制台中显示这些子对象,如下所示:

for (index in arr)
{
for (index2 in arr[index])
{
console.log(JSON.stringify(arr[index][index2],null,4));
}
}

,它为我提供了这些对象和子对象树的输出。

如何在控制台中显示它,因为每个子对象都在换行中,如下所示?

enter image description here

所以没有逗号和双引号,只有“label: value”形式。

最佳答案

很少有 replace() 可以做到这一点。单击运行按钮查看结果。

var arr = [
{
subObj0: {
name: "John",
lastName: "Doe",
age: 50,
nick: "JD",
phone: 123456
},
subObj1: {
name: "Jane",
lastName: "Dee",
age: 30,
nick: "lady",
phone: 654098
},
subObj2: {
name: "Ash",
lastName: "Bash",
age: 33,
nick: "asdB",
phone: 987123
}
},
{
subObj0: {
name: "Asd",
lastName: "Dsa",
age: 10,
nick: "none",
phone: 12
},
subObj1: {
name: "Ivy",
lastName: "Mash",
age: 3,
nick: "IvMash",
phone: 9823
}

}

];

var output = [];
arr.forEach(function (obj, i) {
output.push('obj' + i + ':');
for (var key in obj) {
var value = obj[key];
var str = JSON.stringify(value)
.replace(/[{}"]/g, '') // remove {} and "
.replace(/[,]/g, '\t') // replace commas by tabulations
.replace(/:/g, ': '); // add a nice space after :
output.push(key + ': ' + str);
}
})

output = output.join('\n');
console.log(output);
document.write('<pre>' + output + '</pre>');

关于javascript - 在下一行(新行)中显示嵌套对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33658249/

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