I have a nested object of which I do not know the structure of. For example:
const nestedObject = {
"one": {
"two": {
"three": 3
}
}
}
I wanted to display value of three
.
I have an array like this so that I know how to navigate the object in order to get to three
:
const keys = ["one", "two", "three"]
This doesn't have to be structured this way.
So how do I access one.two.three
given the keys
array above? Or some other data structure. I was thinking of doing a recursion, but it seems too complex and I feel like there is a simple solution out there.
You can do it with a simple Array.prototype.reduce()
function:
const data = {
"one": {
"two": {
"three": 3
}
}
};
const keys = ["one", "two", "three"];
const value = keys.reduce((a, v) => a[v], data);
console.log(value);
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