I want to compare movie[i].genre_ids
with genres array and return an array of string to be pushed in each movie[i].genre_name
as :
genre_name:['','','']
const genres = [
{ id: 28, name: 'Action' },
{ id: 12, name: 'Adventure' },
{ id: 16, name: 'Animation' },
{ id: 35, name: 'Comedy' },
{ id: 80, name: 'Crime' },
{ id: 99, name: 'Documentary' },
{ id: 18, name: 'Drama' },
{ id: 10751, name: 'Family' },
{ id: 14, name: 'Fantasy' },
]
const movie = [
{
genre_ids: [ 16, 18, 12, 14 ],
title: 'Suzume',
// so after comparing id's it will create a new property on each object as genre_name:
// ['Action',Drama,] or nothing if no ids matched .
}
// x20
]
I tried different combinations of array.map
, forEach
, filter
but didn’t manage to find a solution .
4
Answers
This is what I managed to come up with. Used a getter to access the objects own genre IDs, then used findIndex within a map and returned the object’s name property, although I will say this only handles a single movie well as you’d need to define the getter for each object, i’ve included a much tidier example of the below functionality using a class below.
Admittedly this kind of goes far beyond the initial question but someone might find it useful, also much more reusable. Example using a class:
Here’s a solution using the traditional for loop.
An
map()
with a nestedfilter
with anothermap()
would be enough:Demo: