[英]How to get value of keys present in a Json given that the keys are given in an array in Javascript?
Lets say I have an array consisting of keys present in a JSON,假设我有一个由 JSON 中存在的键组成的数组,
const keys = ['Person:name','Person:Address:zip']
Assume the JSON is as below假设 JSON 如下
let data = [
{"Person":[
{"name":"P1",
"Address":{
"zip":"01"}
},
{"name":"P2",
"Address":{
"zip":"02"}
}
]
},
{"Person":[
{"Personname":"P3",
"Address":{
"zip":"03"}
},
{"name":"P4",
"Address":{
"zipcode":"04"}
}
]
},
{"People":[
{"name":"P5",
"Address":{
"zip":"05"}
},
{"name":"P6",
"Address":{
"zip":"06"}
}
]
},
]
Based on the keys array, I will have to traverse through the data dictionary to get its respective values.基于键数组,我将不得不遍历数据字典以获取其各自的值。 For the above example, the result should be like
对于上面的例子,结果应该是这样的
[{"name":'P1','zip':'P1'},{"name":'P2','zip':'P2'},{"name":Null,'zip':'P3'},{"name":'P4','zip':Null}]
I have tried various methods such as recursion and nested loops in the Javascript to no vail to get these results.我已经尝试了各种方法,例如 Javascript 中的递归和嵌套循环,但无法获得这些结果。 Can anyone please help regarding the same?
有人可以帮忙吗?
I'll re use a recent answer of mine.我将重新使用我最近的答案。 I ended up rewriting of course.
当然,我最终重写了。 Anyway, it's doable for one key-path, but it's unclear how to combine 2 or more.
无论如何,一个键路径是可行的,但不清楚如何组合 2 个或更多。 Here's a solution for 1 key-path.
这是 1 个关键路径的解决方案。
const keys = ['Person:name', 'Person:Address:zip'] let data = [{ "Person": [{ "name": "P1", "Address": { "zip": "01" } }, { "name": "P2", "Address": { "zip": "02" } } ] }, { "Person": [{ "Personname": "P3", "Address": { "zip": "03" } }, { "name": "P4", "Address": { "zipcode": "04" } } ] }, { "People": [{ "name": "P5", "Address": { "zip": "05" } }, { "name": "P6", "Address": { "zip": "06" } } ] }, ] function get_by_path(arr, arr_path) { var pointer = arr; var key = arr_path.shift(); while (arr_path.length) { var step = []; pointer.forEach(function(item) { step.push(item? (item[key]? item[key]: {}): {}) }); pointer = step.flat(); key = arr_path.shift(); } var result = pointer.map(function(item) { var obj = {} obj[key] = item? (item[key]? item[key]: null): null return obj }) return result; } keys.forEach(function(key) { var path = key.split(':'); var arr = get_by_path(data, path) console.log (arr); })
.as-console-wrapper { max-height: 100%;important; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.