javascript - 如何从对象中的特定参数从我的对象中找到唯一的对象

标签 javascript underscore.js

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},
};

最佳答案

您可以通过将 Array.fromSet 一起使用来删除重复项,而无需下划线,如下所示:

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);

关于javascript - 如何从对象中的特定参数从我的对象中找到唯一的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55017051/

相关文章:

javascript - 绕过 Firefox 的刷新行为

JavaScript 在数组索引中存储函数调用

javascript - 从 underscore.js 中的数组返回一系列值

javascript - 如何在 d3 js javascript 中制作维恩图的数据结构

javascript - Google Recaptcha 不适用于 ui bootstrap 模式

javascript - Firefox 有时无法在 Canvas 中加载图像

javascript - 从子方法访问父对象

javascript - 如何根据子数组元素状态拆分数组?

javascript - 我怎样才能推迟每个循环的jQuery

javascript - 多次下划线去抖动调用