首页 > 解决方案 > 如何从对象中的特定参数中找到我的对象中的唯一对象

问题描述

var links = {
    1:{source: 0, target: 1},
    2:{source: 0, target: 2},
    3:{source: 0, target: 3},
    4:{source: 0, target: 4},
    5:{source: 0, target: 1},
    6:{source: 0, target: 4}  
};

这是我的数据,我希望通过参数从中获得唯一的对象:目标

var result= {
    1:{source: 0, target: 1},
    2:{source: 0, target: 2},
    3:{source: 0, target: 3},
    4:{source: 0, target: 4},
};

标签: javascriptunderscore.js

解决方案


您可以不使用下划线来执行此操作,方法是使用Array.fromwith aSet删除重复项,如下所示:

const links = [{source: 0, target: 1}, {source: 0, target: 2}, {source: 0, target: 3}, {source: 0, target: 4}, {source: 0, target: 1}, {source: 0, target: 4}]

const res = Array.from(new Set(links.map(JSON.stringify)), JSON.parse);
console.log(res);

但是,如果对象中的另一个属性不同(即它将删除重复的对象),则如果target与另一个属性相同,则上述将保留元素。target

要根据数组中的键删除特定的重复项,您可以使用.reduce

const links = [{source: 0, target: 1}, {source: 0, target: 2}, {source: 0, target: 3}, {source: 0, target: 4}, {source: 0, target: 1}, {source: 0, target: 4}];

const res = Object.values(links.reduce((acc, obj) => {
  const {target} = obj;
  acc[target] = obj;
  return acc;
}, {}));

console.log(res);


推荐阅读