Reputation: 21
If I had a JSON object formatted like this:
{
"CampaignID":5918,
"CampaignFolder":"http://www.Dan.com/campaign/5918-18D/",
"TargetUser.CampaignID":5918,
"TargetUser.GUID":"3dbe24a8-a3e3-4de9-86ab-4940c8e148cc",
}
Once I grab the object and I want to display an alert with a property, I can use alert(CampaignID) and it correctly displays 5918. But if I try alert(TargetUser.CampaignID) it fails. Any ideas?
Upvotes: 1
Views: 43
Reputation: 38552
There are two ways to access properties of object in js
Dot notation and
Bracket notation.
With Dot notation -
property must be a valid JavaScript identifier. For example,
object.$1 is valid, while object.1 is not.
With Bracket notation -
property_name is a string or Symbol. It does not have to be a
valid identifier; it can have any value, including 1foo, !bar!, or
even " " (a space) or a . (dot character)
See MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
Upvotes: 0
Reputation: 2313
The way the object is structured, you're going to need to use bracket notation to access those fields. The object key is "TargetUser.CampaignID" but the JS you're using: TargetUser.CampaignID
means access the object
TargetUser
and access its property CampaignID
when really you just want "TargetUser.CampaignID"
as a string key.
Try something like this
var data = {
"CampaignID":5918,
"CampaignFolder":"http://www.Dan.com/campaign/5918-18D/",
"TargetUser.CampaignID":5918,
"TargetUser.GUID":"3dbe24a8-a3e3-4de9-86ab-4940c8e148cc",
};
alert(data["TargetUser.CampaignID"]);
alert(data["TargetUser.GUID"]);
// data["TargetUser.CampaignID"] is NOT data.TargetUser.CampaignID
// that would look like this: {TargetUser: {CampaignID: 0}}
// not {"TargetUser.CampaignID": 0}
:
Upvotes: 1