How can I access a multi-level property if I am using a variable as the key?
This is not working:
var obj = {
first: {thirst: "yo"},
second: {beckon: "dud"}
}
var key = "first.thirst";
var result = obj[key];
Use console. log or console. dir and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.
When you use a string as a property name in JavaScript, there are no characters that are off-limits: including the period. So you can easily have an object property like this:
var o = {
'first.second.third': 'value';
}
Given this, it's clearly not possible to implement your solution.
However, as long as you don't use periods in your property naming, you can create a function that does this:
function resolve(obj, path){
path = path.split('.');
var current = obj;
while(path.length) {
if(typeof current !== 'object') return undefined;
current = current[path.shift()];
}
return current;
}
Then you could call:
var key = "first.thirst";
var result = resolve(obj, key);
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