在Javascript中动态存储数组中的多个对象

时间:2018-01-11 09:55:37

标签: javascript arrays object

我有一个对象数组:

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]}`
        }
      ];

我需要创建dinamically playlist对象数组,其中有songs个数组中的项目,而不直接指定它们,  像这样的东西:

const playlist = [
    {
      url: `/music/${song}.mp3`,
      title: `${song}`
    }
];

如何处理?我可以使用pushslice方法吗?

3 个答案:

答案 0 :(得分:2)

您已经知道map与您用来创建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);




答案 1 :(得分:0)



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

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




答案 2 :(得分:0)

您可以map覆盖song数组并动态获取playlist

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