skip to Main Content
const data = {
  data: [
    {
      entry: [
        {
          id: 1,
          title: "hello",
        },
        {
          id: 2,
          title: "hi",
        },
      ],
    },
    {
      entry: [
        {
          id: 3,
          title: "hola",
        },
        {
          id: 4,
          title: "hey",
        },
      ],
    },
  ],
};
let rec = data.data.map((d) => {
  return d.entry.map((reco) => {
    return console.log(reco);
  });
});

how can I merge the extract data from mapping function into one array like this?

I tried reduce function and flat function but it doesn’t work

[{id:1 ,  title: "hello"} ,{id:2 , title: "hi"} , {id:3 , title: "hola"} ,{id:4 , title: "hey"} ]

I edit it with better and complete example

2

Answers


  1. You can use Array.prototype.flatMap method to flatten a multidimensional array while mapping it.

    const data = {
      data: [
        {
          entry: [
            {
              id: 1,
              title: "hello",
            },
            {
              id: 2,
              title: "hi",
            },
          ],
        },
        {
          entry: [
            {
              id: 3,
              title: "hola",
            },
            {
              id: 4,
              title: "hey",
            },
          ],
        },
      ],
    }
    const flat = data.data.flatMap(item => item.entry)
    
    Login or Signup to reply.
  2. Another option is to use map to iterate over each item and return the entry array

    Then use flat to merge these arrays into a single array like this:

    let rec = data.data.map(d => d.entry).flat();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search