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.
3
Answers
Basically you need to iterate
pathOfKey
array and traverse the object with key in the array simultaneously.Something like this will do the job.
Also, it can be done with a recursion function
The easiest solution is probably to use
reduce()
.