我有一个对象数组:
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}`
}
];
如何处理?我可以使用push
或slice
方法吗?
答案 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}`
});
);