英文:
Get JSON value from string path
问题
我需要从我的变量中提取JSON值。
例如,我有这个JSON:
const myJson = {
"id": "someID",
"organizations": [
"0": {
"id": "organizationId",
"name": "organizationName"
},
"1": {
...
},
...
]
}
和这个变量:
var pathOfKey = ["organizations","0","id"];
如何从我的变量'pathOfKey'中获取'organizationId'的值?
我事先不知道我的键的路径是什么,但我有一个包含这些信息的变量。
我需要获取数组中所有组织的ID。
英文:
I need to extract a JSON value starting from my variable.
for example i have this json
const myJson = {
"id": "someID",
"organizations": [
"0": {
"id": "organizationId",
"name": "organizationName"
},
"1": {
...
},
...
]
}
and this variable
var pathOfKey = ["organizations","0","id"];
how to get the value of 'organizationId' from my variable 'pathOfKey'?
I don't know in advance what the path to my key is but I have a variable with this information.
I need to get all the organization IDs of my array.
答案1
得分: 1
let obj = {
"a": { "b": "value" }
}
let tmpObj = obj;
let arr = ["a", "b"];
arr.forEach((objKey) => {
if (tmpObj[objKey] !== undefined) {
tmpObj = tmpObj[objKey];
}
});
console.log(tmpObj);
类似这样的代码可以完成任务。也可以使用递归函数来完成。
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let obj = {
"a": {"b": "value"}
}
let tmpObj = obj;
let arr = ["a", "b"];
arr.forEach((objKey) => {
if (tmpObj[objKey] !== undefined) {
tmpObj = tmpObj[objKey];
}
});
console.log(tmpObj);
<!-- end snippet -->
Something like this will do the job.
Also, it can be done with a recursion function
答案2
得分: 0
基本上,您需要迭代pathOfKey
数组,并同时遍历数组中的键以访问对象。
function getValueFromObject(obj, path) {
let currentNode = obj;
for (key of path) {
if (!currentNode.hasOwnProperty(key)) {
return null;
}
currentNode = currentNode[key];
}
return currentNode;
}
getValueFromObject(myJson, pathOfKey)
英文:
Basically you need to iterate pathOfKey
array and traverse the object with key in the array simultaneously.
function getValueFromObject(obj, path) {
let currentNode = obj;
for (key of path) {
if (!currentNode.hasOwnProperty(key)) {
return null;
}
currentNode = currentNode[key];
}
return currentNode;
}
getValueFromObject(myJson, pathOfKey)
答案3
得分: 0
The easiest solution is probably to use reduce()
.
const value = pathOfKey.reduce((item, key) => item[key], myJson);
英文:
The easiest solution is probably to use reduce()
.
const value = pathOfKey.reduce((item, key) => item[key], myJson);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论