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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With