Reputation: 57
I have an array of objects:
const song = songs.map(song => song.title);
const playlist = [
{
url: `/music/${song[0]}.mp3`,
title: `${song[0]}`
},
{
url: `/music/${song[1]}.mp3`,
title: `${song[1]}`
},
{
url: `/music/${song[2]}.mp3`,
title: `${song[2]}`
}
];
I need to create dinamically playlist
array of objects with as many items are in songs
array without specifying them directly,
something like this:
const playlist = [
{
url: `/music/${song}.mp3`,
title: `${song}`
}
];
How to approach this? Can i use push
or slice
methods?
Upvotes: 0
Views: 695
Reputation: 2330
const arr = ['song1', 'song2']
const newArr = []
arr.forEach(song => {
newArr.push({
url: `/music/${song}.mp3`,
title: `${song}`
})
});
console.log(newArr);
Upvotes: 0
Reputation: 136074
You already know about map
that's the same as you'd use to create your playlist
const song = ["Title1","Title2"] // result of songs.map(song => song.title);
const playlist = song.map(title => ({
url: `/music/${title}.mp3`,
title: `${title}`
}));
console.log(playlist);
Upvotes: 3
Reputation: 1521
You can map
over the song
array and get playlist
dynamically like this.
const playlist = song.map( s => ({
url: `/music/${s}.mp3`,
title: `${s}`
});
);
Upvotes: 0