比较对象数组中的属性值

您好,我正在一个项目中继续学习js到这个URL: http : //themapapp.herokuapp.com/这是github页面: https : //github.com/xtatanx/mapApp

在我的代码的一些部分,我需要检查一些属性是否已经存在于一个对象数组中,而且我的属性值等于某些东西,到目前为止,我正在使用的代码是这样的:

// check if property value exist in an array of objects function searchByValue(value, property, array){ for(var i = 0; i < array.length; i++){ if(array[i][property] === value){ return true; } } return false; } 

我这样使用它:

 if(searchByValue('myDestiny', 'id', map.markers)){ map.markers[1].setPosition({ lat: results[0].geometry.location.k, lng: results[0].geometry.location.A }); }else{ createMarker(results[0].geometry.location.k, results[0].geometry.location.A, 'myDestiny'); 

我的问题是,如果实际上我是这样做,或者如果我错了,因为我有时认为该函数没有返回正确的值或不是很好,我会感激,如果你们中的一些人可以给我一些build议在如何实现这一点,或改善它。

编辑

我完成了类似的东西

 Array.prototype.searchBy = function(property, value){ var _property = arguments[0]; var _value = arguments[1]; if(arguments.length === 1){ return Array.prototype.indexOf.apply(this, arguments); } for(var i = 0; i < this.length; i++){ if(this[i][_property] === _value ){ return true; } } return false; }; 

没有使用checkprop部分,因为实际上不知道它是如何工作的o_O。 非常感谢@GameAlchemist和@jshanley

我宁愿将此函数定义为Array的一个方法,为什么不重载indexOf,它将作为带有一个参数的std indexOf,以及带有三个参数的indexOf(value,propertyName,checkProp)。

 var __oldIndexOf = Array.prototype.indexOf ; Array.prototype.indexOf = function() { if (arguments.length==1) return __oldIndexOf.apply(this, arguments); var value = arguments[0]; var property = arguments[1]; var checkProp = arguments[2]; if (!checkProp) { for(var i = 0; i < this.length; i++){ if(this[i][property] === value){ return i; } } else { for(var i = 0; i < this.length; i++){ var thisItem = this[i] ; if (!Object.hasOwnProperty(thisItem, property)) throw('indexOf error : object ' + thisItem + ' has no property ' + property); if(this[i][property] === value){ return i; } } return -1; }; 

所以,对于你的代码,

 if (searchByValue('myDestiny', 'id', map.markers)) { ... 

变成:

 if (map.markers.indexOf('myDestiny', 'id') != -1 ) { ... 

显然你可以存储find的索引,以防你需要它。
我认为,就你而言,你的意思是使用find的指标:

 var destinyIndex = map.markers.indexOf('myDestiny', 'id'); if(destinyIndex != -1){ map.markers[ destinyIndex ].setPosition({ lat: results[0].geometry.location.k, lng: results[0].geometry.location.A }); } else { createMarker(results[0].geometry.location.k, results[0].geometry.location.A, 'myDestiny'); } 

编辑:检查财产存在的想法是@jshanley礼貌

只要你正在search的数组中的每个对象都定义了你检查的属性,你的代码就能正常工作。 否则我会看到遇到问题。 您可以尝试添加一个检查,该属性是在尝试访问其值之前定义的,如下所示:

 function searchByValue(value, property, array){ for(var i = 0; i < array.length; i++){ // check that property is defined first if(typeof array[i][property] !== 'undefined') { // then check its value if(array[i][property] === value){ return true; } } } return false; }