Need help understanding: Filtering an array of objects in Javascript
leanminmachine
Posted on October 4, 2018
I am still trying to wrap my head around filtering an array of objects in Javascript; spent a couple of hours figuring this out.
I have this array of objects being returned to me from my backend. Inside each object, there is a key that has an array of objects as its value. AND inside this array, there's another array of objects, with another array... Yeah it gets pretty confusing.
So something like this:
{
menuEntities: Array(1)
0:
categoryEntities: Array(2)
0:
categoryId: 1
categoryName: "Main"
menuItemEntities: Array(1)
0: {customisableItemEntities: Array(0), description: "Full of delicious beef", enabled: true, foodItemEntities: Array(0), imagePath: "", menuItemName: "Burger"}
length: 1
__proto__: Array(0)
__proto__: Object
1: {categoryId: 2, categoryName: "Drinks", menuItemEntities: Array(1)}
length: 2
__proto__: Array(0)
isSelected: true
menuId: 1
menuName: "Menu 1"
__proto__: Object
length: 1
__proto__: Array(0)
}
What I wanted to do was build a filter function to return true if my input text includes a particular menuItemName. For example, type in burger into my input field and all the restaurants that contain burger would show up in my search results.
I came across this post on Stack Overflow that suggests to use some
After a bit of tinkering, I got this:
this.sortedRestaurants = this.sortedRestaurants.filter(function(
restaurant
) {
if (_.isEmpty(restaurant.menuEntities) == false) {
return restaurant.menuEntities[0].categoryEntities.some(category =>
category.menuItemEntities.some(menuItemEntity =>
menuItemEntity.menuItemName
.toLowerCase()
.includes(val.toLowerCase())
)
);
}
});
And that works for the current use case!
But I don't understand why when I tried forEach initially, this didn't work:
this.sortedRestaurants = this.sortedRestaurants.filter(function(
restaurant
) {
if (_.isEmpty(restaurant.menuEntities) == false) {
return restaurant.menuEntities[0].categoryEntities.forEach(e => {
e.menuItemEntities.forEach(menuItemEntity => {
menuItemEntity.menuItemName
.toLowerCase()
.includes(val.toLowerCase());
});
});
}
});
To me, wouldn't includes still return a true or false value for the case of the forEach function..?
How would you guys write this function better too?
Posted on October 4, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.