36

I have a js object like:

obj = {
  name: 'js',
  age: 20
};

now i want to access name field of obj, but i can only get string 'name', so how to convert 'name' to obj's field name, then to get result like obj.name.

Thank you in advance.

4
  • 3
    obj.name or am I missing the point of the question? Commented Jan 30, 2011 at 5:03
  • 1
    @mhitza: Maybe "name" is stored in a variable and they want to access it like obj.<[evaluate_var]> where <[evaluate_var]> is stored as 'name'? Commented Jan 30, 2011 at 5:05
  • @Brad Christie is right. Commented Jan 30, 2011 at 5:08
  • Thank you all for your answers, these answers are the same and i tried it's correct. Thank you thank you very much. Commented Jan 30, 2011 at 5:14

5 Answers 5

67

You can access the properties of javascript object using the index i.e.

var obj = {
  name: 'js',
  age: 20
};

var isSame = (obj["name"] == obj.name)
alert(isSame);

var nameIndex = "name"; // Now you can use nameIndex as an indexor of obj to get the value of property name.
isSame = (obj[nameIndex] == obj.name)

Check example@ : http://www.jsfiddle.net/W8EAr/

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

Comments

21

In Javascript, obj.name is equivalent to obj['name'], which adds the necessary indirection.

In your example:

var fieldName = 'name'
var obj = {
  name: 'js',
  age: 20
};
var value = obj[fieldName]; // 'js'

Comments

14

Not related at all, but for anyone trying to define object's field name from a string variable, you could try with:

const field = 'asdf'
const obj = {[field]: 123}
document.body.innerHTML = obj.asdf

1 Comment

Nice solution!!
8

It's quite simple, to access an object's value via a variable, you use square brackets:

var property = 'name';
var obj = {name: 'js'};
alert(obj[property]); // pops 'js'

Comments

2

As objects are associative arrays in javascript you can access the 'name' field as obj['name'] or obj[fieldName] where fieldName = 'name'.

Comments

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.