[英]Get values for a matching key recursively from object
I have this json object我有这个 json object
{
"data": {
"user": {
"user_info": {
"id": "AoGC2HQ9vedHmzcMX"
},
"product": [
{
"node": {
"id": "NzcxNzU2ODU1ODM1",
"feedback": {
"raters": {
"nodes": [
{
"id": "1",
"name": "Dan"
},
{
"id": "2",
"name": "Allen"
},
{
"id": "3",
"name": "Williams"
}
]
},
"commentors": {
"nodes": [
{
"id": "001",
"name": "Kent"
},
{
"id": "002",
"name": "Jay"
}
]
}
}
}
}
]
}
}
}
So how do I make it to get values of id
If the parent property matches the desired key name, In this example I want to get all id's from raters.nodes
only.那么如何获取
id
的值 如果父属性与所需的键名匹配,在此示例中,我只想从raters.nodes
获取所有 id。
so expected result is所以预期的结果是
[1,2,3]
I know can do obj.data.user.product[0].node.feedback.raters.nodes
and loop through that, but that is not how I want and the object tree occasionally changes.我知道可以执行
obj.data.user.product[0].node.feedback.raters.nodes
并循环执行,但这不是我想要的,object 树偶尔会发生变化。
I have used this recursive function我用过这个递归 function
const recursiveSearch = (obj, searchKey, results = []) => {
const r = results;
Object.keys(obj).forEach(key => {
const value = obj[key];
if(key === searchKey && typeof value !== 'object'){
r.push(value);
}else if(typeof value === 'object'){
recursiveSearch(value, searchKey, r);
}
});
return r;
};
//returns all id's
While it works, it returns all id values, so how do I improve it?虽然它可以工作,但它会返回所有 id 值,那么我该如何改进它呢? If not, how do I make this possible?
如果没有,我该如何做到这一点?
I think you want to really do this in 2 steps,..我想你真的想分两步做到这一点,..
First make a function to get the root node your looking for, and then you can just use map like normal.首先制作一个 function 来获取您要查找的根节点,然后您可以像往常一样使用 map。
Below is an example.下面是一个例子。
var data = JSON.parse("{\"data\":{\"user\":{\"user_info\":{\"id\":\"AoGC2HQ9vedHmzcMX\"},\"product\":[{\"node\":{\"id\":\"NzcxNzU2ODU1ODM1\",\"feedback\":{\"raters\":{\"nodes\":[{\"id\":\"1\",\"name\":\"Dan\"},{\"id\":\"2\",\"name\":\"Allen\"},{\"id\":\"3\",\"name\":\"Williams\"}]},\"commentors\":{\"nodes\":[{\"id\":\"001\",\"name\":\"Kent\"},{\"id\":\"002\",\"name\":\"Jay\"}]}}}}]}}}"); function getRoot(data, search) { function get(path, data) { for (const [k, v] of Object.entries(data)) { if (v instanceof Object) { const pp = `${path}.${k}`; if (pp.slice(-search.length) === search) { return v; } const r = get(`${path}.${k}`, v); if (r) return r; } } } return get('', data); } const r = getRoot(data, 'raters.nodes'); console.log(r && r.map(i => i.id));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.