javascript - 如何从对象中的特定参数中找到我的对象中的唯一对象
问题描述
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
with 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);
推荐阅读
- python - 如何根据两个条件遍历数据框?
- python - 使用 Pandas 跨数据帧的条件替换
- validation - F# - 这是验证和保持两个界限之间的值的好方法吗?
- html - 在角度如何以一种方式修剪值数据绑定
- oracle - Oracle RAC RMAN 备份未写入 NFS 共享
- java - 尝试比较日期时发生异常 - 即使我设置了日期,Nullpointerexception 和 get 方法也返回空值
- reactjs - 如何使用具有 DD/MMM/YYYY 格式或自定义输入字段的材料 UI 选择器 KeyboardDatePicker
- python - 我们如何防止 FASTAPI 中的 html 注入?
- python - 使用任何需要互联网的东西时 Kivy 应用程序崩溃
- apache-flink - 在 Flink SQL 中加入连续查询