How does js get the key of type object

  • 2020-03-30 01:49:02
  • OfStack

A recent problem:
var obj = {"name1":" Zhang SAN ","name2":" Li si "}; 
var key = "name1"; 
var value = obj.key;//The "undefined"
value = obj.name1;//I got "Joe"

So what I want to do is dynamically assign the key, and then I want to get the correct value of the key. But that's not going to work. Obj. key is going to look for the value of "key" under obj, and of course it's not going to be there.
So, I came up with the method of traversing object properties in js:
function printObject(obj){ 
//Obj = {"cid":"C0","ctext":" district "};
var temp = ""; 
for(var i in obj){//The javascript for/in loop iterates over the properties of the object
temp += i+":"+obj[i]+"n"; 
alert(temp);//Results: cid:C0 n ctext: district and county

In this way, we can clearly know the key and value of an object in js.
So going back to the question, how do you dynamically assign the key, and then get the corresponding value in the form of obj.key?
In fact, there is a hint in printObject above, that is to use obj[key] method, key can be dynamic, so I solve the problem above.
Finally, there's another method that works: eval("obj."+key).


There are two methods in js to get the corresponding value in an object according to the dynamic key:
Var key = "name1"; [key] the var value = obj.
Var key = "name1"; Var value = eval (" obj "+ key);

Related articles: