let obj = [
{ id : 1 },
{ id : 10 },
{ brand : 12 },
{ id : 15 },
{ id : 18 },
{ image_link : 'some link' },
{ price : 10 },
{ brand : 111 },
{ image_link : 'some link 2' }
];
我有一个对象数组。2我想过滤这个对象,这样我就可以得到一个没有重复键对象。
我正在尝试这个:
let uniqueIds = [];
let unique = obj.filter( (element ) => {
let key = Object.keys(element)[0];
let isDuplicate = uniqueIds.includes(element.key);
if (!isDuplicate) {
uniqueIds.push(element.key);
return true;
}
return false;
});
console.log( unique )
但每次它都告诉我:
[ { id: 1 } ]
预期输出:
[
{ id : 18 },
{ price : 10 },
{ brand : 111 },
{ image_link : 'some link 2' }
];
3条答案
按热度按时间ia2d9nvy1#
您可以根据对象的索引键是否为数组中最后一个出现的索引键(使用
lastIndexOf
检查)来筛选数组:m1m5dgzv2#
原因是您需要使用
key
而不是element.key
注意:您似乎有一个排印错误,
brnad
不是brand
kxeu7u2r3#
您已经在两个地方使用了
element.key
,它应该只是key
。因为你需要最后一个重复的元素,所以你需要对输入数组做一个逆操作,然后再对唯一数组做一个逆操作。