Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading