我有一個對象數組。每個對象都有一個名爲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