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
.
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?
4
Answers
Instead of
map
, you could only useArray#flatMap
and check ifitem
has propertysubItems
return its items.You could do it with
filter
andmap
.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.
You can use
Array::reduce
to collect items: