2016-10-04 78 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

相关问题