0

I'm having trouble figuring out how to access a variable in a multilevel deep object using a function like

getLanguageVariable("form.passwordSwitch.disabled");

and the following object as sample

var language = {
    "de": {
        "form": {
            "passwordSwitch": {
                "enabled": "Der Klartext-Modus ist aus. Aktivieren?",
                "disabled": "Der Klartext-Modus ist an. Deaktivieren?"
            }
        }
    }
}

Tried to split the string at the dot character, then creating a string representation of

language["de"]["form"]["passwordSwitch"]["enabled"]

which is used to access objects and it's properties. I used this code:

var stack = variableIdentifier.split(".");
var reference = "";

for (i = 0; i < stack.length; i++) {
    if (i == 0) reference += stack[i];
    else reference += "[\"" + stack[i] + "\"]";
}

Any clues how to dynamically access the properites of an object, given you don't know how deep it is?

Matt
  • 74,352
  • 26
  • 153
  • 180
René Schindhelm
  • 1,887
  • 2
  • 14
  • 15
  • possible duplicate of [javascript convert dotnotation string into objects](http://stackoverflow.com/questions/6704737/javascript-convert-dotnotation-string-into-objects) – Esailija Jul 19 '12 at 13:49

2 Answers2

1

I implemented the same in pythons a couple of days ago. Basically, When you do not know how deep the object is, use a recursion pattern.

function getPath(obj, path)
{
    path = path.split('.');
    return _getpath(obj, path);
}

function _getPath(obj, path)
{
    if(!path.length)
        return obj;

    p = path.shift();

    if(obj[p])
        return _getPath(obj[p], path);

    return undefined;
}
yadutaf
  • 6,840
  • 1
  • 37
  • 48
0

You can do something like this;

function getLanguageVariable(path) {
    // I don't know how you determine "de", but this should be
    // easy to customise
    var next = language.de;

    // Make path = ["form","passwordSwitch","disabled"];
    path = path.split(/\./);

    // Loop over path, and for each pass, set next to the next key
    // e.g. next = next["form"];
    //      next = next["passwordSwitch"]
    //      next = next["disabled"]
    while (path.length && (next = next[path.shift()]) && typeof next === "object" && next !== null);

    // Check we have used all the keys up (path.length) and return
    // either undefined, or the value
    return path.length ? undefined : next;
}

For future information, note what you have is an Object defined via Object Literal Syntax, and is not JSON at all; for more info see What is the difference between JSON and Object Literal Notation?

Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180
  • Wow. Thank you. This is like magic to me. Never would have though of using `while` for recursion like you have suggested. Works like a charm ♥. And thanks for pointing out the difference between JSON and Object Literal Notation! – René Schindhelm Jul 19 '12 at 17:25