我正在寻找一种删除数组其他元素的方法。 但是我不知道该怎么做。
这是我的数组:
musics: [
{
id: 1,
cover: require('~/assets/images/cover/music/ali_zand_vakili_jadeh_shab.jpg'),
title: 'جاده شب',
artist: 'علی زند وکیلی',
source: 'http://media.mtvpersian.net/2019/Mar/21/Ali%20Zand%20Vakili%20-%20Jadeh%20Shab.mp3'
},
{
id: 2,
cover: require('~/assets/images/cover/music/amin_hayaei_divoone_misazi.jpg'),
title: 'دیوونه میسازی',
artist: 'امین حیایی',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Amin_Hayaei/Singles/amin_hayaei_divoone_misazi.mp3'
},
{
id: 3,
cover: require('~/assets/images/cover/music/emad_talebzadeh_maghrour.jpg'),
title: 'مغرور',
artist: 'عماد طالب زاده',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Emad_Talebzadeh/Singles/emad_talebzadeh_maghrour.mp3'
},
{
id: 4,
cover: require('~/assets/images/cover/music/farzad_farzin_jazzab.jpg'),
title: 'جذاب',
artist: 'فرزاد فرزین',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Farzad_Farzin/Singles/farzad_farzin_jazzab.mp3'
},
{
id: 5,
cover: require('~/assets/images/cover/music/hamid_sefat_ajayeb_shahr_merat_remix.jpg'),
title: 'عجایب شهر رمیکس',
artist: 'حمید صفت',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Hamid_Sefat/Singles/hamid_sefat_ajayeb_shahr_merat_remix.mp3'
}
],
如何删除ID为3的元素以外的所有元素?
答案 0 :(得分:1)
您可以使用过滤器:https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
musics = musics.filter (x => x.id == 3)
答案 1 :(得分:1)
var musics= [{id: 1,cover: '~/assets/images/cover/music/ali_zand_vakili_jadeh_shab.jpg',title: 'جاده شب',artist: 'علی زند وکیلی',source: 'http://media.mtvpersian.net/2019/Mar/21/Ali%20Zand%20Vakili%20-%20Jadeh%20Shab.mp3'},
{id: 2,cover: '~/assets/images/cover/music/amin_hayaei_divoone_misazi.jpg',title: 'دیوونه میسازی',artist: 'امین حیایی',source: 'https://cdnmrtehran.ir/media/mp3s_128/Amin_Hayaei/Singles/amin_hayaei_divoone_misazi.mp3'},
{id: 3,cover: '~/assets/images/cover/music/emad_talebzadeh_maghrour.jpg',title: 'مغرور',artist: 'عماد طالب زاده',source: 'https://cdnmrtehran.ir/media/mp3s_128/Emad_Talebzadeh/Singles/emad_talebzadeh_maghrour.mp3'},
{id: 4,cover: '~/assets/images/cover/music/farzad_farzin_jazzab.jpg',title: 'جذاب',artist: 'فرزاد فرزین',source: 'https://cdnmrtehran.ir/media/mp3s_128/Farzad_Farzin/Singles/farzad_farzin_jazzab.mp3'},
{id: 5,cover:'~/assets/images/cover/music/hamid_sefat_ajayeb_shahr_merat_remix.jpg',title: 'عجایب شهر رمیکس',artist: 'حمید صفت',source: 'https://cdnmrtehran.ir/media/mp3s_128/Hamid_Sefat/Singles/hamid_sefat_ajayeb_shahr_merat_remix.mp3'}]
var result =[];
musics.forEach(function(item){
if(item.id == 3){
result.push(item);
}
});
console.log(result);
答案 2 :(得分:0)
要删除所有偶数索引元素,可以使用以下命令:
musics = musics.filter((e, i) => i % 2 == 0)
要删除奇数,只需用!=更改==