我正在寻找具有密钥
的过滤对象这是我的对象
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的键的对象。
建议一些帮助。
答案 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
。
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;