首页 > 解决方案 > 仅当对象不存在时,如何向 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"}
]

标签: javascriptreactjs

解决方案


您可以使用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);


推荐阅读