Javascript:查找数组中具有某些属性和值的所有对象

时间:2016-10-04 22:10:26

标签: javascript arrays javascript-objects

我有一个对象数组。每个对象都有一个名为available的布尔属性,以及任意数量的其他属性。我知道available属性存在,但我不知道其他属性是什么。例如:

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;
}

有人可以提供任何反馈意见吗?谢谢。

2 个答案:

答案 0 :(得分: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}))

答案 1 :(得分:0)

您可以使用array .filter()方法。对于旧版浏览器,您可以使用Lodash

myObjects.filter(function(x) { return x["available"] === true && x["color"] === 100 })
相关问题