var arr = [{id: 21,label: 'Banana',},{id: 22,label: 'Apple',}]
/* note : data is the actual object that matched search criteriaor undefined if nothing matched */
var data = arr.find(function(ele) {return ele.id === 21;});
if (data) {console.log('found');console.log(data); // This is entire object i.e. `item` not boolean}
/* note : doesExist is a boolean thats true or false depending on of whether the data was found or not */var doesExist = arr.some(function(ele) {return ele.id === 21;});
为了将一个对象与另一个对象进行比较,我结合了一个for in loop(用于循环遍历对象)和一些()。您不必担心数组越界等问题,这样可以节省一些代码。可以在.一些上找到文档这里
var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected productsvar theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];var objectsFound = [];
for(let objectNumber in productList){var currentId = productList[objectNumber].id;if (theDatabaseList.some(obj => obj.id === currentId)) {// Do what you need to do with the matching value hereobjectsFound.push(currentId);}}console.log(objectsFound);
vendors = [{Name: 'Magenic',ID: 'ABC'},{Name: 'Microsoft',ID: 'DEF'} //and so on goes array...];
// filter returns a new array, we instantly check if the length// is longer than zero of this newly created arrayif (vendors.filter(company => company.Name === 'Magenic').length ) {console.log('I contain Magenic');}
// some would be a better option then filter since it directly returns a booleanif (vendors.some(company => company.Name === 'Magenic')) {console.log('I also contain Magenic');}
if (!Array.prototype.some) {Array.prototype.some = function(fun, thisArg) {'use strict';
if (this == null) {throw new TypeError('Array.prototype.some called on null or undefined');}
if (typeof fun !== 'function') {throw new TypeError();}
var t = Object(this);var len = t.length >>> 0;
for (var i = 0; i < len; i++) {if (i in t && fun.call(thisArg, t[i], i, t)) {return true;}}
return false;};}
* Note that this uses the popular lodash library to achieve the simplest/shortest possible solution. I'm offering this as an alternative to the existing vanilla JS solutions, for those who are interested.