I've encountered a problem recently:
The code copy is as follows:
var obj = {"name1":"Zhang San","name2":"Li Si"};
var key = "name1";
var value = obj.key;//Get "undefined"
value = obj.name1;//Get "Zhang San"
Actually, I want to dynamically assign a value to the key and then get the value of the key as much as it is. But this approach doesn't work. Obj.key will look for the value corresponding to "key" under obj, and of course it can't be found.
So, I thought of a way to traverse object properties in js:
The code copy is as follows:
function printObject(obj){
//obj = {"cid":"C0","ctext":"District and county"};
var temp = "";
for(var i in obj){//Loop through the object's properties with javascript for/in
temp += i+":"+obj[i]+"/n";
}
alert(temp);//Result: cid:C0 /n ctext: District and County
}
In this way, you can clearly know what the key and value of an object in js are respectively.
Going back to the question just now, how to dynamically assign a value to the key and then get the corresponding value in obj.key?
In fact, there is a prompt in the printObject above, that is, the obj[key] method is used, the key can be dynamic, which solves the problem I raised above.
Finally, there is another method that can be done, that is: eval("obj."+key).
Summarize:
There are two ways to get the corresponding value in a certain object based on dynamic key in js:
1. var key = "name1";var value = obj[key];
2. var key = "name1";var value = eval("obj."+key);