Home > Blockchain >  How to map through a deeply nested array of objects?
How to map through a deeply nested array of objects?

Time:05-23

const my_arr = [
   {id: 1, arr: [{subId: 1, value: 1}],
   {id: 2, arr: [{subId: 2, value: 2}],
   {id: 3, arr: [{subId: 3, value: 1}],
]

how do I map over this array my_arr and then map over arr to return an array like so:

[
  {subId: 1, value: 1},
  {subId: 3, value: 1},
]

basically filtering out only where values are 1 and then returning only that sub object

I've tried doing

my_arr.map((x) => x.map((y) => y.value === 1 ? y : null)) 

CodePudding user response:

You can try this approach with flatMap and filter

const my_arr = [
   {id: 1, arr: [{subId: 1, value: 1}]},
   {id: 2, arr: [{subId: 2, value: 2}]},
   {id: 3, arr: [{subId: 3, value: 1}]},
]

const result = my_arr.flatMap(item => item.arr).filter(item => item.value === 1)

console.log(result)

CodePudding user response:

Your current approach maps over the outer array, and then uses an inner map to map over the inner array. Since .map() always returns an array, you'll end up mapping your objects from your outer array to other arrays, which you don't want. You can instead use .flatMap() which will combine/join the returned inner arrays into one array. Rather than using .map() as your inner method though, you should use .filter() to create an array of objects that have a valuue of 1, which then gets merged into your outer array created by .flatMap():

const my_arr = [
   {id: 1, arr: [{subId: 1, value: 1}]},
   {id: 2, arr: [{subId: 2, value: 2}]},
   {id: 3, arr: [{subId: 3, value: 1}]},
];

const res = my_arr.flatMap(
  ({arr}) => arr.filter(({value}) => value === 1)
);
console.log(res);

CodePudding user response:

const my_arr = [
   {id: 1, arr: [{subId: 1, value: 1}] },
   {id: 2, arr: [{subId: 2, value: 2}] },
   {id: 3, arr: [{subId: 3, value: 1}] },
]

const output = my_arr
  .filter(({ arr }) =>
    arr.some(({value}) => value === 1)
  ).reduce((acc, { arr }) => acc.concat(arr), [])
  
console.log(output)

  • Related