user592638
user592638

Reputation:

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?

Upvotes: 0

Views: 85

Answers (4)

Hassan Imam
Hassan Imam

Reputation: 22524

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

Upvotes: 1

yajiv
yajiv

Reputation: 2941

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

Upvotes: 0

Keith
Keith

Reputation: 144

This will do the trick:

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

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191936

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

Upvotes: 2

Related Questions