Reputation: 13206
I have an array with the following structure
let pageComponents = { pages: [ { "components": [ ... ] }, { "components": [ ... ] } ] };
See Remove null entries from array of objects for the contents of components
.
I've tried to run the following filter method on it, but the object array returns null afterwards. Any idea on how I can fix it?
static deleteEmptyComponentsOnMultiplePages(components) {
return components['pages'].forEach(obj => {
obj['components'].filter(item => item !== null);
}
);
}
Upvotes: 0
Views: 58
Reputation: 3502
ForEach
is iterator only and its return type is void. you need to use other iterator methods like map
let pageComponents = {
pages: [
{
"components": [1, 2, 4, null]
},
{
"components": ['a', 'b', null, 'd']
}
]
};
function deleteEmptyComponentsOnMultiplePages(components) {
return components.map(obj => {
return obj.components.filter(item => item !== null);
});
}
console.log(deleteEmptyComponentsOnMultiplePages(pageComponents.pages))
Upvotes: 0
Reputation: 36564
forEach
doesn't return anything it just loops. Here you need to use map()
.
You also need to use return
inside the callback of map()
otherwise you will get an array of undefined
static deleteEmptyComponentsOnMultiplePages(components) {
return components['pages'].map(obj => {
return obj['components'].filter(item => item !== null);
});
}
You can exclude {}
of map()
and return implicitly
static deleteEmptyComponentsOnMultiplePages(components) {
return components['pages'].map(obj => obj['components'].filter(item => item !== null));
}
You can use destructuring for more cleaner code
static deleteEmptyComponentsOnMultiplePages({pages}) {
return pages.map(({components}) => components.filter(item => item !== null));
}
Upvotes: 5