0

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?

2
  • Your question is not entirely clear. Are you trying to build up playlist with as many items are in song array without specifying them directly? Commented Jan 11, 2018 at 9:57
  • Yes. I want create playlist array of objects with as many items are in songs array without specifying them directly. Commented Jan 11, 2018 at 9:59

3 Answers 3

3

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, simple and clear. Accepted this answer as correct.
0

You can map over the song array and get playlist dynamically like this.

const playlist = song.map( s => ({
      url: `/music/${s}.mp3`,
      title: `${s}`
    });
);

Comments

0

const arr = ['song1', 'song2']
const newArr = []

arr.forEach(song => {
  newArr.push({
    url: `/music/${song}.mp3`,
    title: `${song}`
  })
});
console.log(newArr);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.