繁体   English   中英

遍历带有嵌套数组的对象数组

[英]Looping through a array of objects with nested arrays

给出以下简单示例:

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数组数组,然后通过扩展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); 

您可以将array#reducearray#forEach

 const testdata = [ { id: "001", name: "Bob", comments: [ { id: "01", text: "Hello World" }, { id: "02", text: "Hello Mars" } ] } ], result = testdata.reduce((r, {comments}) => { comments.forEach(o => r.push({...o})); return r; },[]); console.log(result); 

这将达到目的:

testdata.map(i => i.comments.map(comment => console.log(comment)));

如果您只想显示评论,则可以使用forEach实现此目的(forEach不会创建额外的变量)

 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"}]}]; testdata.forEach(x => x.comments.forEach(y => console.log(y))); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM