如何通过乘以数组/对象值来过滤对象数组 [英] How to filter array of object by multiples array/objects values

查看:87
本文介绍了如何通过乘以数组/对象值来过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to filter an array of objects, like this:

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":[

   ],
}

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

So, in this case, the result could be:

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

我已阅读其他链接:如何通过检查多个值来过滤数组/对象,但我似乎无法适应它我的情况。

I've already read this other link: How to filter an array/object by checking multiple values, but I can not seem to adapt it to my case.

提前致谢!

编辑:不要求电力财产的条件现在

The condition on "power" property is not requested now

编辑2:对不起,我忘了指出过滤器对象可以为单个属性设置多个值,如下所示:

EDIT 2: Sorry, I've forgot to indicate that filter object can have multiple values for single property, like this:

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


推荐答案

解决方案使用 Array.filter Array.indexOf Object.keys 函数:

The solution using Array.filter, Array.indexOf and Object.keys functions:

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

这篇关于如何通过乘以数组/对象值来过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆