循环使用嵌套数组的对象数组

时间:2018-04-05 11:48:02

标签: javascript loops ecmascript-6

给出这个简单的例子:

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)});

输出包含注释的嵌套数组的最佳方法是什么?

4 个答案:

答案 0 :(得分:2)

使用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);

答案 1 :(得分:1)

您可以将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);

答案 2 :(得分:0)

这样可以解决问题:

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

答案 3 :(得分:0)

如果你只是想显示评论然后使用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)));