I have an array of objects as per below.
songs = [
{
track_name: "name of track" ,
track_genres: ["chamber pop","indie pop"] },
{
track_name: "name of track 2" ,
track_genres: ["dutch r&b","indie soul", "indie pop"] },
{
track_name: "name of track 3" ,
track_genres: ["indie pop","chamber pop","indie soul"] }
]
I have another mapping object that looks like this
genres = [
{
name: "Pop",
children: [{name:"chamber pop"},{name:"indie pop"}]
},
{
name: "R&B",
children: [{name:"dutch r&b"}]
},
{
name: "Soul",
children: [{name:"indie soul"}]
}
]
What I want to do is for each track, go through the track genres, and use the "genres" variable to assign the parent genres for each track. Parent genre ideally shouldn’t be repeated.
Expected Output:
const songs = [
{
track_name: "name of track",
track_genres: ["chamber pop", "indie pop"],
parent_genres: ["Pop"] },
{
track_name: "name of track 2",
track_genres: ["dutch r&b", "indie soul", "indie pop"],
parent_genres: ["R&B","Soul","Pop"] },
{
track_name: "name of track 3",
track_genres: ["indie pop", "chamber pop", "indie soul"],
parent_genres: ["Pop", "Soul"] }
];
2
Answers
I’d first transform your
genres
array into aMap
which maps the children to the genre name:this can be done by
flatMap
-ing yourgenres
array and then for each child object return a key-value pair that includes the genre-name as the value and the child name as the key:Once you have that map built, you can map through
songs
and add yourparent_genres
property and set it to an array. This array is a mapped version of yourtrack_genres
where you used the above Map to get the associated genre for each item. Then you can wrap this in a Set and spread the result back into array to remove any duplicates: