Javascript - object key & # 8594; value

var obj = { a: "A", b: "B", c: "C" } console.log(obj.a); // return string : A 

but I want to go through a variable like

 var name = "a"; console.log(obj.name) // but return undefined 

How to do it?

+43
javascript
Feb 15 '11 at 7:35
source share
4 answers

Use notation [] for string representations of properties:

 console.log(obj[name]); 

Otherwise, it searches for the "name" property, not the "a" property.

+60
Feb 15 2018-11-15T00:
source share

obj ["a"] is equivalent to obj.a so use obj [name], you get "A"

+11
Feb 15 2018-11-11T00:
source share

Use this syntax:

 obj[name] 

Note that obj.x same as obj["x"] for all valid JS identifiers, but the latter form accepts all strings as keys (not just valid identifiers).

 obj["Hey, this is ... neat?"] = 42 
+5
Feb 15 2018-11-15T00:
source share

https://jsfiddle.net/sudheernunna/tug98nfm/1/

  var days = {}; days["monday"] = true; days["tuesday"] = true; days["wednesday"] = false; days["thursday"] = true; days["friday"] = false; days["saturday"] = true; days["sunday"] = false; var userfalse=0,usertrue=0; for(value in days) { if(days[value]){ usertrue++; }else{ userfalse++; } console.log(days[value]); } alert("false",userfalse); alert("true",usertrue); 
0
Dec 11 '17 at 13:24
source share



All Articles