JavaScript-从对象数组中获取唯一的对象


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

我有一组物体。我想过滤这个对象,这样我就可以得到一个没有重复键的对象。

我正在尝试:

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

您可以根据对象的键是否是该键在数组中的最后一次出现(使用lastIndexOf检查(来筛选数组:

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' }
];
const keys = obj.map(o => Object.keys(o)[0])
const result = obj.filter((o, i) => keys.lastIndexOf(Object.keys(o)[0]) == i)
console.log(result)

原因是您需要使用key而不是element.key

注意:你似乎有一个打字错误brnad不是brand

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' }
];
let uniqueIds = [];
let unique = obj.filter( (element ) => {

let key = Object.keys(element)[0];                
let isDuplicate = uniqueIds.includes(key);
if (!isDuplicate) {
uniqueIds.push(key);
return true;
}
return false;   
});
console.log( unique )

您在两个地方使用了element.key,它应该只是key

由于您需要最后一个重复元素,因此需要对输入数组进行反转,然后再对唯一数组进行另一次反转。

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' }
];
let uniqueIds = [];
// reverse the input array before start filtering
obj.reverse()
let unique = obj.filter( (element ) => {

let key = Object.keys(element)[0];                
let isDuplicate = uniqueIds.includes(key);
if (!isDuplicate) {
uniqueIds.push(key);
return true;
}
return false;   
});
// to make the output order according to the input array
unique.reverse()
// to make the input array to the initial order 
obj.reverse()
console.log(unique)

最新更新