Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten nested array of object using es6

I have this array of object, within it I have another array of object, how to get:

[
  { id: "5a60626f1d41c80c8d3f8a85" },
  { id: "5a6062661d41c80c8b2f0413" },
  { id: "5a60626f1d41c80c8d3f8a83" },
  { id: "5a60626f1d41c80c8d3f8a84" }
];

From:

[
  {
    id: 1,
    country: [
      {
        id: "5a60626f1d41c80c8d3f8a85"
      },
      {
        id: "5a6062661d41c80c8b2f0413"
      }
    ]
  },
  {
    id: 2,
    country: [
      {
        id: "5a60626f1d41c80c8d3f8a83"
      },
      {
        id: "5a60626f1d41c80c8d3f8a84"
      }
    ]
  }
];

without using a forEach and a temp variable?

When I did:

(data || []).map(o=>{
  return o.country.map(o2=>({id: o2.id}))
})

I got the same structure back.

like image 885
Jane Emelia Avatar asked Jan 25 '18 04:01

Jane Emelia


People also ask

Which method is used to convert nested arrays to object?

toString() method is used to convert: an array of numbers, strings, mixed arrays, arrays of objects, and nested arrays into strings.


1 Answers

Latest edit

All modern JS environments now support Array.prototype.flat and Array.prototype.flatMap

const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];

console.log(
  data.flatMap(
    (elem) => elem.country
  )
)

Old answer

No need for any ES6 magic, you can just reduce the array by concatenating inner country arrays.

const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];

console.log(
  data.reduce(
    (arr, elem) => arr.concat(elem.country), []
  )
)

If you want an ES6 feature (other than an arrow function), use array spread instead of the concat method:

const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];

console.log(
  data.reduce(
    (arr, elem) => [...arr, ...elem.country], []
  )
)

Note: These suggestions would create a new array on each iteration.

For efficiency, you have to sacrifice some elegance:

const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];

console.log(
  data.reduce(
    (arr, elem) => {
      for (const c of elem.country) {
        arr.push(c);
      }
      return arr;
    }, []
  )
)
like image 155
nem035 Avatar answered Oct 04 '22 01:10

nem035