I encountered a problem recently:
var obj = {"name1 ":"Zhang San","name2":"李思"};
var key = "name1";
var value = obj.key;//got "undefined"
value = obj .name1;//got "Zhang San"
Actually, I want to dynamically assign a value to the key, and then get the value corresponding to the key. But this approach doesn't work. obj.key will look for the value corresponding to the key "key" under obj. Of course, it cannot be found.
So, I thought of the method of traversing object properties in js:
function printObject(obj){
//obj = {"cid":"C0","ctext":"District and County"};
var temp = "";
for( var i in obj){//Use javascript’s for/in loop to traverse the properties of the object
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.
Going back to the previous question, how do you dynamically assign a value to a key and then get the corresponding value in the form of obj.key?
In fact, there is a hint in the above printObject, which is to use the obj[key] method. The key can be dynamic, which solves the problem I raised above.
Finally, there is another method that can be used, that is: eval("obj." key).
Summary:
There are two ways to get the corresponding value in an object based on dynamic key in js:
1. var key = "name1";var value = obj[ key];
2. var key = "name1"; var value = eval("obj." key);