开发者

How to refer to object fields with a variable? [duplicate]

This question already has answers here: Accessing an object pr开发者_开发问答operty with a dynamically-computed name (19 answers) Closed 3 years ago.

Let's asume that I have an object:

var obj = {"A":"a", "B":"b", "x":"y", "a":"b"}

When I want to refer to "A" I just write obj.A

How to do it when I have key in a variable, i.e.:

var key = "A";

Is there any function that returns a value or null (if key isn't in the object)?


Use bracket notation, like this:

var key = "A";
var value = json[key];

In JavaScript these two are equivalent:

object.Property
object["Property"];

And just to be clear, this isn't JSON specific, JSON is just a specific subset of object notation...this works on any JavaScript object. The result will be undefined if it's not in the object, you can try all of this here.


How about:

json[key]

Try:

json.hasOwnProperty(key)

for the second part of your question (see Checking if a key exists in a JavaScript object?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜