如何通过多个数组/对象的值筛选对象数组

4

我需要过滤一个对象数组,就像这样:

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

我已经阅读了另一个链接:如何通过检查多个值来过滤数组/对象,但我似乎无法将其适应到我的情况。
提前致谢!
编辑:现在不需要对“功率”属性进行条件限制
编辑2:抱歉,我忘记指出过滤对象可以具有单个属性的多个值,例如:
var filter = {
   "family":[
       "Applique", "Faretto", "Lanterne"
   ],
   ...
   "volt":[
        "12", "230"
   ],
   ...
}

3
请提供您已经尝试的代码。 - Andy
2个回答

5

使用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"
    }
]

非常感谢您的回复,但我忘记提及一些细节,请查看我帖子中的第二次编辑。再次感谢。 - Andrea
太棒了!正是我所需要的!非常感谢! :) - Andrea

0
尝试使用lodash_.filter函数。
对于筛选大于/小于的情况,可以参考这里的示例: _.filter(users, _.conforms({ 'age': _.partial(_.gt, _, 38) }));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接