简体   繁体   中英

How to map through a deeply nested array of objects?

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

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)

Your current approach maps over the outer array my_arr , 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. However, rather than using .map() as your inner method though, you should use .filter() to create an array of objects that have a value of 1 , which then gets merged into your resulting outer array created by the .flatMap() method:

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

Since you are dealing with nested structure, you will have to get little creative.

  • First you will have to filter the array.
  • Inside it, you can use .some to check if your condition matches and return matching
  • Now you have the filtered list but you still need to format your output. You can use .reduce and concat arr of every item

This will be useful if you have multiple items in arr .

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM