EricC EricC - 1 year ago 116
Javascript Question

JavaScript: Access object multi-level property using variable

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];

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download