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?
Use notation [] for string representations of properties:
[]
console.log(obj[name]);
Otherwise, it searches for the "name" property, not the "a" property.
obj ["a"] is equivalent to obj.a so use obj [name], you get "A"
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.x
obj["x"]
obj["Hey, this is ... neat?"] = 42
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);