简体   繁体   中英

Looping through a array of objects with nested arrays

Given this simple example:

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

I would like to output all the comments for this object:

With this I get the id and the name

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

What is the best way to output the nested array that holds the comments?

Get an array of comments arrays with Array.map() , then flatten by spreading into 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); 

You can use array#reduce with array#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)));

If you just want to display comments then using forEach you can achieve this(forEach not create extra variable)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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