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

toiithl6  于 2022-10-30  发布在  Java
关注(0)|答案(3)|浏览(195)
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' }
];
ia2d9nvy

ia2d9nvy1#

您可以根据对象的索引键是否为数组中最后一个出现的索引键(使用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)
m1m5dgzv

m1m5dgzv2#

原因是您需要使用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 )
kxeu7u2r

kxeu7u2r3#

您已经在两个地方使用了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)

相关问题