How to Get Value in an Object's Key Using a Variable Referencing That Key?

I have an object and I can reference key a as in the following:

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

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

I want to get the value by using a variable to reference the object key as below:

var name = "a";
console.log(obj.name) // this prints undefined, but I want it to print "A"

How can I do this?

7 Answers

Use [] notation for string representations of properties:

console.log(obj[name]);

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

0

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

2

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
0

You can get value of key like this...

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

console.log(obj.a);

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

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

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 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
var o = { cat : "meow", dog : "woof"};
var x = Object.keys(o);

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

IAB

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest