gpt4 book ai didi

javascript - 循环遍历具有嵌套数组的对象数组

转载 作者:行者123 更新时间:2023-11-28 17:33:35 24 4
gpt4 key购买 nike

给出这个简单的例子:

const testdata = [
{
id: "001",
name: "Bob",
comments: [
{
id: "01",
text: "Hello World"
},
{
id: "02",
text: "Hello Mars"
}
]
}
];

我想输出该对象的所有评论:

这样我就得到了 id 和名字

testdata.map(i => { console.log(i.id + i.name)});

输出保存注释的嵌套数组的最佳方式是什么?

最佳答案

使用Array.map()获取comments数组的数组,然后按 spreading 展平进入Array.concat() :

const testdata = [{"id":"001","name":"Bob","comments":[{"id":"01","text":"Hello World"},{"id":"02","text":"Hello Mars"}]},{"id":"002","name":"Sara","comments":[{"id":"03","text":"Hello Jupiter"},{"id":"04","text":"Hello Moon"}]}];

const comments = [].concat(...testdata.map((d) => d.comments));

console.log(comments);

关于javascript - 循环遍历具有嵌套数组的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49671639/

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