2016-10-04 100 views
-1

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

有人可以提供任何意見嗎?謝謝。

+1

退房'.filter' - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – Adam

+0

聽起來像下劃線的'.find()'方法 – dandavis

回答

0

您可以使用數組.filter()方法。對於舊的瀏覽器可以使用Lodash

myObjects.filter(function(x) { return x["available"] === true && x["color"] === 100 }) 
+0

這不是他們要求的。 'isAvailable'應該接受一個動態過濾器對象。 – georg

1

您可以使用filter()every()返回期望的結果。

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}, 
 
] 
 

 
function isAvailable(obj) { 
 
    var keys = Object.keys(obj); 
 
    return myObjects.filter(function(e) { 
 
    return keys.every(function(k) { 
 
     return e.available && e.hasOwnProperty(k) && obj[k] == e[k] 
 
    }) 
 
    }) 
 
} 
 

 
console.log(isAvailable({color:100})) 
 
console.log(isAvailable({color:100, length:86})) 
 
console.log(isAvailable({size:13}))

+0

更好地在'filter'之外緩存'Object.keys(obj)'。 – Oriol

+0

...並使'myObjects'成爲一個參數,不要使用全局 – georg

相關問題