163

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?

0

10 Answers 10

205

Use [] notation for string representations of properties:

console.log(obj[name]);

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

Sign up to request clarification or add additional context in comments.

Comments

29

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

2 Comments

Please attention that obj[name] will return obj.name which is undefined.
Use backticks `` if you're writing short amounts of code
18

You can get value of key like these ways...

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

console.log(obj.a);

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

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

1 Comment

thank you, i personally like the obj.a syntax [+1]
13

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

Comments

4

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

Comments

3

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

Comments

3
productList = {
        "name": "Title"
}
var key = "name";

console.log(productList[key])

productList is an arbitraty object with only one key. the key variable holds the same key as a string.

Using the [] you can access the value dynamically.

Comments

3

fyi, if the type of the object is not known it's a little trickier:

    var name = "a";
    console.log(obj[name as keyof typeof obj]);

(refer to this post)

Comments

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

Comments

-1

You can simply do obj[key]. You can skip spread operator(...{}) to copy the original object.

function getVal({...obj},key) {
  return obj[key]
}


let _obj = {
  a_key : 'a_val',
  b_key : 'b_val',
} 

console.log(getVal(_obj, 'a_key'))

9 Comments

If you can skip it, then why still do it?
@Bergi - In JS, passing object to a function is pass by reference by default and we should not pass object as reference to a function unless you have a strong reason to do so. Passing object to function as value is best practice and you can do so by using spread (...) operator. OP did not asked about it so I advised to just ignore it. Thanks for asking. Regards
Copying the object needlessly is a waste of time.
"Passing object to function as value is best practice" - no, it absolutely is not.
@Unmitigated - Not at-least in the world of react.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.