javascript - 仅当对象不存在时,如何向 Array 注入对象?
问题描述
我有我的空数组
locations = []
我有另一个包含位置和城市的数组
Data = [
{ location: "01" , city: "01"},
{ location: "01" , city: "02"},
{ location: "03" , city: "03"},
{ location: "04" , city: "04"},
{ location: "01" , city: "01"},
{ location: "01" , city: "01"}
]
如何循环遍历数组Data[]
并添加对象locations[]
而不像第一个对象和最后两个对象一样重复它
locations = [
{ location: "01" , city: "01"},
{ location: "01" , city: "02"},
{ location: "02" , city: "02"},
{ location: "03" , city: "03"},
{ location: "04" , city: "04"}
]
解决方案
您可以使用Array.reduce()
过滤掉重复项并获得一个唯一的对象数组,locations
:
var Data = [
{ location: "01" , city: "01"},
{ location: "01" , city: "02"},
{ location: "03" , city: "03"},
{ location: "04" , city: "04"},
{ location: "01" , city: "01"},
{ location: "01" , city: "01"}
];
var locations = Data.reduce((acc, obj)=>{
var exist = acc.find(({location, city}) => obj.location === location && obj.city === city);
if(!exist){
acc.push(obj);
}
return acc;
},[]);
console.log(locations);
推荐阅读
- java - 嵌套类:`OuterClass.this.someAttribute`?
- python - 如何在 Chrome 中打开 URL 并获取其内容?
- ssh - 无法通过 SSH 连接到数字海洋新水滴
- r - 如何根据ggplot中数字列的值为绘制点分配颜色渐变
- tensorflow - 在 Keras 中未检测到 GCP GPU
- angular - node_modules/@types/googlemaps/index.d.ts 中的错误——元组类型元素列表不能为空
- python-3.x - Matplotlib 中的极坐标图,通过映射到笛卡尔坐标
- firebase-realtime-database - 无法删除 Firebase 数据库控制台中的节点错误
- python - 硒单击href按钮
- django - 在 ManyToManyField 上注释 FilteredRelation 不会返回任何内容