I have this JSON
var myJSON = {
"a": {
"b": {
"c": {
"Foo": "Bar"
}
}
}
}
I also have this array:
var path = ["a", "b", "c", "foo"]
How can I use the path to get Bar?
I have this JSON
var myJSON = {
"a": {
"b": {
"c": {
"Foo": "Bar"
}
}
}
}
I also have this array:
var path = ["a", "b", "c", "foo"]
How can I use the path to get Bar?
Check out Array.prototype.reduce(). This will start at myJSON and walk down through each nested property name defined in path.
var myJSON = {
"a": {
"b": {
"c": {
"Foo": "Bar"
}
}
}
};
var path = ["a", "b", "c", "Foo"]; // capitalized Foo for you...
var val = path.reduce((o, n) => o[n], myJSON);
console.log("val: %o", val);
Have a variable that stores the value of the object, then iterate through the path accessing the next property in that variable until the next property is undefined, at which point the variable holds the end property.
var val = myJSON;
while (path.length) {
val = val[path.shift()];
}
console.log(val);
function access(json, path, i) {
if (i === path.length)
return json;
return access(json[path[i]], path, i + 1);
}
to use:
access(myJSON, path, 0)
var myJSON = {
"a": {
"b": {
"c": {
"Foo": "Bar"
}
}
}
}
var path = ["a", "b", "c", "Foo"]
var findViaPath = function (path, object) {
var current = object;
path.forEach(function(e) {
if (current && e in current) {
current = current[e];
} else {
throw new Error("Can not find key " + e)
}
})
return current;
}
findViaPath(path, myJSON);