Skip to content
Advertisement

How can I filter nested objects and arrays with JavaScript?

My use case is something like this.

  1. I have an array that has an object.
  2. That each object has an array called menu
  3. Again that menu array has objected.
  4. That each object has an array dish_has_categories
  5. In dish_has_categories array, if there is an object with CategoryId is equal to 8 I want to filter out that root object.

My original data object

JavaScript

My expect result is

JavaScript

what I’ve done up to now is

JavaScript

I have no idea how to deep filter inside nested objects and arrays. Hope my question is clear to you all.

Advertisement

Answer

You can use filter and some

Here nested some is used to check whether any of dish_has_categories has CategoryId equal to '8', if it is true then we include that menu in final output else we don’t

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement