我有一个对象数组。每个对象都有一个名为available
的布尔属性,以及任意数量的其他属性。我知道available
属性存在,但我不知道其他属性是什么。例如:Javascript:查找具有某些属性和值的数组中的所有对象
var myObjects = [
{color:100, size:12, available:true},
{color:100, size:13, available:false},
{color:100, size:18, available:true},
{color:110, size:12, available:true},
{length:86, available:true},
]
我需要一个函数isAvailable()
可以采取任何属性值对,并返回那些匹配,可供哪些对象。举例来说,如果我问了可用的对象与100
颜色,它将返回只由第一和第三对象的数组:
>> isAvailable({color:100})
Array [ {color:100, size:12, available:true}, {color:100, size:18, available:true} ]
但如果我问的对象具有100
和颜色它的长度为86
,或者仅仅是13
的大小,它会返回一个空数组。
>> isAvailable({color:100, length:86}) // there are no objects with both of these properties
Array [ ]
>> isAvailable({size:13}) // there is a matching object, but it is not available
Array [ ]
我有一个功能工作,但它不是很漂亮。对javascript没有太大的经验,我不确定是否有更好的方法来解决这个问题。
function isAvailable(options) {
var availableObjects = [];
// get the number of objects
var numObjects = myObjects.length;
// get the number of options that were given
var numOptions = Object.keys(options).length;
// loop through each object
for (var i = 0; i < numObjects; i++) {
var thisObject = myObjects[i];
// default the matching to false
var match = false;
// loop through each option and check if the current object has the option and, if so, if the values are the same.
for (var x = 0; x < numOptions; x++) {
var thisOption = Object.keys(options)[x]
if (thisObject.hasOwnProperty(thisOption) && thisObject[thisOption] == options[thisOption]) {
match = true;
} else {
match = false;
break;
}
}
if (match == true && thisObject.available == true) {
availableObjects.push(thisObject);
}
}
return availableObjects;
}
有人可以提供任何意见吗?谢谢。
退房'.filter' - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – Adam
听起来像下划线的'.find()'方法 – dandavis