Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Access object multi-level property using variable [duplicate]

Tags:

javascript

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];
like image 719
EricC Avatar asked Jun 14 '14 16:06

EricC


People also ask

How you would access an inner property in a JavaScript object that itself points to an array of JavaScript objects?

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.


1 Answers

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);
like image 159
Ethan Brown Avatar answered Nov 23 '22 19:11

Ethan Brown