[英]Loop through an object of objects and extract key value that equals something specific?
I am trying to avoid dependencies such as loaddash (_.filter) and use pure javascript. 我试图避免诸如loaddash(_.filter)之类的依赖,而是使用纯JavaScript。
Basically I have an object of objects, and I need to loop through and filter out all that dont have a parent_id of a specific value. 基本上,我有一个对象对象,并且我需要遍历并过滤掉所有不具有特定值的parent_id的对象。
var filterBy = 50
var obj = {
256: {
name: john
parent_id: 50
},
341: {
name: dwit
parent_id: 50
},
398: {
name: ryan
parent_id: 30
},
421: {
name: jack
parent_id: 50
}
}
with the result being 结果是
var filteredOBJ = {
256: {
name: john
parent_id: 50
},
343: {
name: dwit
parent_id: 50
},
421: {
name: jack
parent_id: 50
}
}
const result = {};
for(const [key, val] of Object.entries(obj)) {
if(val.parent_id === filterBy) {
result[key] = val;
}
}
Just turn what you described into code and you're done. 只需将您描述的内容转换为代码即可。
Here's an implementation of a simple filter in ES6 : 这是ES6中简单过滤器的实现:
let myObj = {
256: {
name: "john",
parent_id: 50
},
341: {
name: "dwit",
parent_id: 50
},
398: {
name: "ryan",
parent_id: 30
},
421: {
name: "jack",
parent_id: 50
}
}
let result = {};
Object.entries(myObj).forEach( ([key, value]) => {
if(key != 398) // condition over keys
result[key] = value;
})
console.log(result);
If you like the loadash approach, but want to use javascript, reduce()
on the Object.entries()
will give you nice functional approach, although the above forEach
solutions probably win for readabilty. 如果您喜欢loadash方法,但想使用javascript,则
Object.entries()
上的reduce()
Object.entries()
将为您提供不错的功能性方法,尽管上述forEach
解决方案可能会提高可读性。
var filterBy = 50 var obj = {256: {name: 'john',parent_id: 50},341: {name: 'dwit',parent_id: 50},398: {name: 'ryan',parent_id: 30},421: {name: 'jack',parent_id: 50}} let r = Object.entries(obj).reduce((a, [k, v]) => v.parent_id === filterBy ? Object.assign(a, {[k]: v}) : a, {}) console.log(r)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.