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.from
与 Set
一起使用来删除重复项,而无需下划线,如下所示:
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/