如何通过乘以数组/对象值来过滤对象数组

时间:2016-05-03 12:11:53

标签: javascript jquery arrays object

我需要过滤一个对象数组,如下所示:

var models = [
    {
      "family": "Applique",
      "power":"8",
      "volt":"12",
      "color":"4100",
      "type":"E27",
      "ip":"20",
      "dimensions":"230x92"
    },
    {
      "family": "Lanterne",
      "power":"20",
      "volt":"230",
      "color":"2700",
      "type":"R7S",
      "ip":"44",
      "dimensions":"230x92"
    },
    {
      "family": "Applique",
      "power":"50",
      "volt":"230",
      "color":"",
      "type":"GU10",
      "ip":"20",
      "dimensions":"227x227"
    }
]

基于这样的对象:

var filter = {
   "family":[
      "Applique", "Faretto", "Lanterne"
   ],
   "power":{
      "less":[
          "30"
      ],
      "greater":[

      ],
      "equal":[

      ]
   },
   "volt":[
      "12", "230"
   ],
   "color":[

   ],
   "type":[

   ],   
   "ip":[
      "20"
   ]
   "dimensions":[

   ],
}

因此,在这种情况下,结果可能是:

{
  "family": "Applique",
  "power":"8",
  "volt":"12",
  "color":"4100",
  "type":"E27",
  "ip":"20",
  "dimensions":"230x92"
}

我已经阅读了其他链接:How to filter an array/object by checking multiple values,但我似乎无法适应我的情况。

提前致谢!

编辑:" power"现在不要求财产

编辑2:抱歉,我忘了表明过滤器对象可以有多个单一属性值,如下所示:

var filter = {
   "family":[
       "Applique", "Faretto", "Lanterne"
   ],
   ...
   "volt":[
        "12", "230"
   ],
   ...
}

2 个答案:

答案 0 :(得分:4)

使用Array.filterArray.indexOfObject.keys函数的解决方案:

var result = models.filter(function(obj){
    var matched = true;
    Object.keys(obj).forEach(function(k){
        if (k === "power") {  // The condition on "power" property is not requested now
            return false;
        }
        if (filter[k] && filter[k].length && filter[k].indexOf(obj[k]) === -1) {
            matched = false;
        }
    });
    return matched;
});

console.log(JSON.stringify(result, 0, 4));

console.log输出:

[
    {
        "family": "Applique",
        "power": "8",
        "volt": "12",
        "color": "4100",
        "type": "E27",
        "ip": "20",
        "dimensions": "230x92"
    }
]

答案 1 :(得分:0)

尝试lodash' s _.filter

对于过滤大于/小于它们的过滤示例here

_.filter(users, _.conforms({ 'age': _.partial(_.gt, _, 38) }));