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 filter and map nested array in a new data model?

I have an object which contains an array, inside this array I want to filter the objects based on a type.

I got this working with .filter. Then I want to add a property (array) of this object into a new object.

Basically what I want is filtering subItems by type and add subitems in the same structure as currentElement.

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

If a item contains sub items, this sub items must be added to a object in the same structure like currentElement.
newElement is what I want as result.

const currentElement = {
  items: [
   {
    name: 'item',
    subItems: [
     {
      name: 'item 1',
      type: 'item'
     },
     {
      name: 'item 2',
      type: 'item'
     }
    ]
    type: 'subItems'
   },
   {
    name: 'item',
    type: 'item'
   }
  ]
}

to be, what I expect:

const newElement= {
      items: [
         {
          name: 'item 1',
          type: 'item'
         },
         {
          name: 'item 2',
          type: 'item'
         }
      ]
    }

filter subItems and map as new element.

What I tried:

returnItems() {
    const items= this.currentElement.items.filter(item => item.type === 'subItems')
.map({subItems}) => subItems);
    
    return items;
 }

But this doesn’t return what I expect, this returns an Array in Array. While I expect something like the newElement.

How can I tackle this?

>Solution :

returnItems() {
  const items = this.currentElement.items
    .filter(item => item.type === 'subItems')
    .flatMap(item => item.subItems);
    
  return items;
}

The issue here is that the map function is returning an array of subItems arrays, which results in an array of arrays. Instead, you want to "flatten" these into a single array. You can achieve this with the flat or flatMap function.

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