0

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?

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

I like this one. Nice.
You can do testdata.reduce((acc, {comments}) => acc.concat(...comments), []) also.
0

This will do the trick:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.