Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string as object's field name in javascript

Tags:

javascript

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.

like image 311
ywenbo Avatar asked Jan 30 '11 04:01

ywenbo


People also ask

Can I convert string to object JavaScript?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.

Can an object property be a string?

Property keys must be strings or symbols (usually strings). Values can be of any type.

Is string object in JavaScript?

In JavaScript, strings are not objects. They are primitive values.


2 Answers

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/

like image 63
Chandu Avatar answered Oct 07 '22 21:10

Chandu


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' 
like image 35
Mathieu Ravaux Avatar answered Oct 07 '22 21:10

Mathieu Ravaux