繁体   English   中英

javascript - 如何检查数组中对象的存在

[英]javascript - How to check for existence of object in array

如何在javascript中检查数组中是否存在对象?

这是一个简单的例子。 假设我有一个如下所示的数组:

let array = [{"zone": "WV", "zip": "56855"}, 
  {"zone": "SC", "zip": "28031"}, 
  {"zone": "TN", "zip": "84755"}]

现在我想在我的array添加一个对象,但前提是它尚不存在。

例如,尝试添加此对象将失败:

let addMe = [{"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}]

但这会成功

[{"zone": "SC", "zip": "55555"}, {"zone": "TN", "zip": "88888"}]

显然, addMe是一个需要逐步执行的数组,在某些对象上失败,在其他对象上取得成功。

我试图使用filter但它不像我想要的那样工作。 而且我必须逐步通过原始数组以及逐步通过我想要添加的对象,创建嵌套for循环,这让人感到困惑。 这是我的尝试:

array.filter(function(item){
  addMe.forEach(function(element){
    if(item.zone != element.zone && zone.zip!= element.zip){
      array.push(element);
    }
  });
});

有没有更好的办法?

一种替代办法是函数some捕获至少一个对象,其中不every值是相等的。

 let array = [{"zone": "WV", "zip": "56855"}, {"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}], addMe = [{"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}]; addMe.forEach(o => { if (!array.some(a => Object.keys(a).every(k => a[k] === o[k]))) array.push(o); }); console.log(array); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

通过使用underscore.js 你可以尝试这样的事情:

 let array = [ {"zone": "WV", "zip": "56855"}, {"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"} ]; let addMe1 = [{"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}]; let addMe2 = [{"zone": "SC", "zip": "55555"}, {"zone": "TN", "zip": "88888"}]; // This will fail. addMe1.forEach( item => !_.findWhere(array, item) ? array.push(item) : null); // This will success. addMe2.forEach( item => !_.findWhere(array, item) ? array.push(item) : null); console.log(array); 
 <script src="https://fastcdn.org/Underscore.js/1.8.3/underscore-min.js"></script> 

或者,您可以使用JSON.stringify比较两个对象的所有值。

所以我们首先filter到没有任何重复,通过使用some我们比较字符串化的对象。

let array = [{"zone": "WV", "zip": "56855"}, 
  {"zone": "SC", "zip": "28031"}, 
  {"zone": "TN", "zip": "84755"}]

const newObj = [{"zone": "WV", "zip": "55444"}, 
  {"zone": "SC", "zip": "28031"}]

array = array.concat(newObj.filter(x => !array.some(y => JSON.stringify(y) === JSON.stringify(x))))

console.log(array)

您可以在ECMAScript 6中使用本机javascript,find()方法:

  let array = [{"zone": "WV", "zip": "56855"}, {"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}],
  addMe = [{"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}];

  addMe.forEach(place => {
    if (array.find((element) => element.zone == place.zone) === undefined) {
      array.push(place);
    }
  });

除了已经给出的正确答案之外,你的if语句中有一个错误(item.zip而不是zone.zip)以及对filter方法的误解(返回true表示保持而false表示离开)。 所以,如果坚持使用过滤器:

let valids = addMe.filter(function(element) {
  for(let i=0; i < array.length; i++) {
     if(item.zone === element.zone && item.zip === element.zip) return false // throw the item
  }
  return true; // keep the item
});

array.push(valids);

对于没有过滤器的现代浏览器, findIndex有一个更短的方法:

for(let i = 0; i < addMe.length; i++) {
   let index = array.findIndex(item => item.zone === element.zone && item.zip === element.zip);
   // will return index of the matching item or -1

   if(index < 0) array.push(element); // Add it and you're done

   // or better to avoid array search inflation on already added elements
   // It will remove element from addMe
   addMe.splice(i,1);
}
// In case use of splice
array.push(addMe);

some方法也是处理数组而不是addMe的好方法。

有快速开发,运行缓慢的修复,每次都需要搜索所有对象的所有键。 或者有一个开发缓慢,运行速度快的解决方案,可以构建某种查找,因此您不需要进行所有循环查找。 这是一个简单的想法(更多是一个想法的开头)。

创建一个保持一组所有已知键/值对的类(或对象)。 这只是用一个分隔符(它不应出现在数据中)来连接它们。 现在在添加之前,只需在Set进行常量查找即可检查:

 let array = [ {"zone": "WV", "zip": "56855"}, {"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"} ] class unqiueCollection { constructor(arr, sep = "_"){ this.arr = [] this.sep = sep this.unique_keys = new Set arr.forEach((item) => this.add(item)) } add(item) { let key = item.zip + '_' + item.zone if (!this.unique_keys.has(key)) { this.unique_keys.add(key) this.arr.push(item) } else { console.log("already in array") } } } let coll = new unqiueCollection(array) // won't add coll.add({"zone": "SC", "zip": "28031"}) coll.add({"zip": "28031", "zone": "SC"}) // will add coll.add({"zone": "AK", "zip": "99577"}) console.log(coll.arr) 

这假设所有对象都只包含zip和zone。 如果您的项目更复杂,那么制作密钥的关键和逻辑当然需要更复杂来决定什么是唯一的。

你可以做到这一点

    if(myArray !== undefined && myArray.length != 0) { 
     //your code here 
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM