JS how to get the key value in the object type

Source: Internet
Author: User
Tags eval

This article mainly introduced JS to get the object type in the key value of the method, the need for friends can refer to the

Recently encountered a problem:

The code is as follows:

var obj = {"name1": "John", "name2": "Dick"};

var key = "Name1";

var value = obj.key;//got "undefined"

Value = obj.name1;//got "John"

In fact, I want to dynamically assign value to the key, and then get the value of how much key is right. But this approach does not work, Obj.key will find obj under key for "key" corresponding to the value, the result of course is not found it.

So, I think of JS in the Traversal object properties method:

The code is as follows:

function PrintObject (obj) {

obj = {"cid": "C0", "Ctext": "Counties"};

var temp = "";

for (var i in obj) {//For/in looping through the properties of the object with JavaScript

Temp + + i+ ":" +obj[i]+ "n";

}

Alert (temp);//Result: cid:c0 N ctext: Counties

}

In this way, you can clearly know what is the key and value of JS one object is what.

Back to the problem, how to dynamically assign a value, and then obj.key to get the corresponding value?

In fact, the above PrintObject has a hint, that is, using the Obj[key] method, key can be dynamic, so that solves the problem I raised above.

Finally, there is another way to do this: eval ("obj.") +key).

Summarize:

JS in the dynamic key to obtain the corresponding value of the object is two methods:

First, var key = "Name1"; var value = Obj[key];

Second, var key = "Name1"; var value = eval ("obj.") +key);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.