Lodash获得所有拥有密钥的对象

时间:2017-03-09 14:37:39

标签: javascript arrays json node.js lodash

我正在寻找具有密钥

的过滤对象

这是我的对象

 var mydevices=    {
      "Object1": {
        "name": "name1",
        "category": "laptop"
      },
      "Object2": {
        "name": "name2",
        "category": "laptop"
      },
      "Object3": {
        "name": "name3",
        "category": "Desktop"
      },
      "Object4": {
        "name": "name4",
        "category": "Mobile"
      }
    }

我的过滤器键是数组

var filterKeyArray=["Mobile","laptop"]

我希望对每个对象的类别应用过滤器。

因此,过滤器将返回具有来自filterKeyArray的键的对象。

建议一些帮助。

2 个答案:

答案 0 :(得分:1)

使用lodash,您可以使用pickBy从对象中选择属性并传递使用includes的函数来过滤掉不在数组中的值。这将创建新对象,不会更改原始对象。

var mydevices = {"Object1":{"name":"name1","category":"laptop"},"Object2":{"name":"name2","category":"laptop"},"Object3":{"name":"name3","category":"Desktop"},"Object4":{"name":"name4","category":"Mobile"}}
var filterKeyArray=["Mobile","laptop"]

var result = _.pickBy(mydevices, e => _.includes(filterKeyArray, e.category))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

答案 1 :(得分:0)

使用Object.keys()Array#map迭代mydevices属性,并检查指定的元素是否在category数组中提到filterKeyArray值。

ES6 解决方案,无需lodash

&#13;
&#13;
var mydevices = {Object1:{name:"name1",category:"laptop"},Object2:{name:"name2",category:"laptop"},Object3:{name:"name3",category:"Desktop"},Object4:{name:"name4",category:"Mobile"}},
    filterKeyArray = ["Mobile", "laptop"]

Object.keys(mydevices).forEach(v => filterKeyArray.some(c => c == mydevices[v].category) ? null : delete mydevices[v]);

console.log(mydevices);
&#13;
&#13;
&#13;