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?

333897 次浏览

Use [] notation for string representations of properties:

console.log(obj[name]);

否则它将查找“ name”属性,而不是“ a”属性。

使用以下语法:

obj[name]

注意,对于所有有效的 JS 标识符,obj.xobj["x"]相同,但是后者接受所有字符串作为键(不仅仅是有效的标识符)。

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

obj["a"]等于 obj.a 所以使用 obj[name]你会得到“ A

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


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

内务部

我使用以下语法:

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

错误:

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

get message:

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

你可以像这样得到 keyvalue..。

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


console.log(obj.a);


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


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

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


console.log(productList[key])

productList是一个只有一个键的任意对象。 key变量与字符串持有相同的键。

使用 []可以动态访问该值。