Here is what I am trying to do:
movies = [{'title': 'a', 'genres': ['Romance', 'Comedy']},
{'title': 'b', 'genres': ['Drama', 'Comedy']},
{'title': 'c', 'genres': ['Action', 'Adventure']}]
filters = ['Romance', 'Drama']
Desired contents of filtered array:
[{'title': 'a', 'genres': ['Romance', 'Comedy']},
{'title': 'b', 'genres': ['Drama', 'Comedy']}]
The issue is that I am not sure how to filter an array given another array of values. If 'filters' was just a single string, then I could just do:
movies.filter(x => x.genres.includes(filters))
But this obviously won't work if filters is an array of values.
Any help is much appreciated.
How do you filter nested array of objects? The filter() method creates a new array with all elements that pass the test implemented by the provided function. Approach 1: This approach uses filter() method to filter the nested object in JavaScript.
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
You can use the Object. keys() function to convert the object's keys into an array, and accumulate the filtered keys into a new object using the reduce() function as shown below. const obj = { firstName: 'Jean-Luc', lastName: 'Picard', age: 59 }; // { firstName: 'Jean-Luc', lastName: 'Picard' } Object.
JavaScript's Objects are not iterable like arrays or strings, so we can't make use of the filter() method directly on an Object . filter() allows us to iterate through an array and returns only the items of that array that fit certain criteria, into a new array.
You're very close. It looks like what you need is the array .some
method. That method will return true if it's callback is true for any item, so what you need is for "some" genre to be included in the filter list:
movies = [{
'title': 'a',
'genres': ['Romance', 'Comedy']
},
{
'title': 'b',
'genres': ['Drama', 'Comedy']
},
{
'title': 'c',
'genres': ['Action', 'Adventure']
}
]
filters = ['Romance', 'Drama']
//[{'title': 'a', 'genres': ['Romance', 'Comedy']},
// {'title': 'b', 'genres': ['Drama', 'Comedy']}]
console.log(movies.filter(x => x.genres.some(g => filters.includes(g))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With