Home > Web Front-end > JS Tutorial > body text

How to get the key value in object type in js_javascript skills

WBOY
Release: 2016-05-16 16:59:33
Original
1393 people have browsed it

I encountered a problem recently:

Copy code The code is as follows:

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:
Copy code The code is as follows:

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);
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template