How to refer to object fields with a variable? [duplicate]
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?)
精彩评论