[javascript] Javascript - object key->value

var obj = {
   a: "A",
   b: "B",
   c: "C"
}

console.log(obj.a); // return string : A

but i want to get by through a variable like this

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

How to do this?

This question is related to javascript

The answer is


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);

You can get value of key like this...

_x000D_
_x000D_
var obj = {
   a: "A",
   b: "B",
   c: "C"
};

console.log(obj.a);

console.log(obj['a']);

name = "a";
console.log(obj[name])
_x000D_
_x000D_
_x000D_


Use this syntax:

obj[name]

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

obj["Hey, this is ... neat?"] = 42

Use [] notation for string representations of properties:

console.log(obj[name]);

Otherwise it's looking for the "name" property, rather than the "a" property.


I use the following syntax:

objTest = {"error": true, "message": "test message"};

get error:

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

get message:

 name = "message"
 console.log(objTest[name]);

var o = { cat : "meow", dog : "woof"};
var x = Object.keys(o);

for (i=0; i<x.length; i++) {
  console.log(o[x[i]]);
}

IAB


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