假设我们有一些关于像这样的数组中的某些图像的数据-
const arr = [{
'image': "jv2bcutaxrms4i_img.png",
'gallery_image': true
},
{
'image': "abs.png",
'gallery_image': true
},
{
'image': "acd.png",
'gallery_image': false
},
{
'image': "jv2bcutaxrms4i_img.png",
'gallery_image': true
},
{
'image': "abs.png",
'gallery_image': true
},
{
'image': "acd.png",
'gallery_image': false
}];我们需要编写一个包含一个这样的数组的JavaScript函数。
我们的函数应从数组中删除具有“ image”属性重复值的对象。
为此的代码将是-
const arr = [{
'image': "jv2bcutaxrms4i_img.png",
'gallery_image': true
},
{
'image': "abs.png",
'gallery_image': true
},
{
'image': "acd.png",
'gallery_image': false
},
{
'image': "jv2bcutaxrms4i_img.png",
'gallery_image': true
},
{
'image': "abs.png",
'gallery_image': true
},
{
'image': "acd.png",
'gallery_image': false
}];
const buildUnique = (arr = []) => {
const unique = [];
arr.forEach(obj => {
let found = false;
unique.forEach(uniqueObj => {
if(uniqueObj.image === obj.image) {
found = true;
};
});
if(!found){
unique.push(obj);
};
});
return unique;
};
console.log(buildUnique(arr));输出结果
控制台中的输出将是-
[
{ image: 'jv2bcutaxrms4i_img.png', gallery_image: true },
{ image: 'abs.png', gallery_image: true },
{ image: 'acd.png', gallery_image: false }
]