0

I want to access a Javascript Object dynamicly.

Example:

example: { 
    name: "dev.pus", 
    year: 2012, 
    os: "linux" 
}

This isn't anything new. Now you normaly can access properties of the "example" with:

console.log(example.name);
// or
console.log(example.year);

But what is if I want to take the attribute dynamicly? For example, another var (lets assume the user sets it) should decide which property we want:

var = "name";
console.log(example.var); // error
console.log(example[var]); // error

What is the way to go?

2
  • 10
    example[variable] should work. You're just choosing the worst name in the history of variable names... var is a reserved keyword in Javascript. Commented Jul 10, 2012 at 7:41
  • Btw, don't replace var by package, or new or function :) Commented Jul 10, 2012 at 7:47

1 Answer 1

3

Your example should work if you'll change your variable name (var is reserved).

var key = 'name';
console.log(example[key]);

You can also iterate over your object to get all keys:

for (var item in example){
    if (example.hasOwnProperty(item)){
      console.log(example[item]);
    }
}  

http://jsfiddle.net/bC9XJ/

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, I have updated the post. To the beginning I thought this was a Javascript issue but now this seems to be related with jquery. Maybe you remember the pattern from the other thread ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.