Morgan Freeman
Morgan Freeman

Reputation: 141

Access Javascript Object With a String

Let's say I have this global object:

funky_baby = {
    "wonk wonk": "clunk", 
    "zipee": "chugga chugga", 
    "ahoooga": "boioioioing"
};

And I want to access it using the string "funky_baby". I am currently using this method:

window["funky_baby"];

This doesn't seem like it will be very multi-browser friendly to me. Is there a better way to accomplish this task?

Upvotes: 0

Views: 97

Answers (3)

Dragos Bobolea
Dragos Bobolea

Reputation: 782

As explained in this question's accepted answer, your code is perfectly fine, as long as you don't want to iterate through its members in IE8 or earlier. You can, however, declare it as

window.funky_baby = {"wonk wonk", "zipee", "ahoooga"};

And you've solved that too :)

Upvotes: 4

Albert Xing
Albert Xing

Reputation: 5788

If you are trying to access a variable through its name a as a string (leaving aside that the object is not a real object), window["varName"] is the best way to do it.

This is only particularly useful if the variable you are trying to access varies in itself (e.g. access window["blue"] in one case but window["yellow"] in another:

var blue   = "Blue",
    yellow = "Yellow";

function (color) {
    console.log(window[color]);
}

If you are simply attempting to access that variable, just type the variable name:

console.log(funky_baby);

Upvotes: 2

LetterEh
LetterEh

Reputation: 26696

That is perfectly "multi-browser" friendly.

obj["string"];

var string = "string";
obj[string];
obj.string;

All are totally valid. Even if you're accessing window, as long as you can guarantee that this program is meant for a web-browser, as window is guaranteed to be a part of the global DOM in that case.

Except that you don't have a real object, there.

var obj = {
    key1 : value1,
    key2 : value2
};

If you didn't have the values there, it would break.

Upvotes: 3

Related Questions