I am writing one function on Javascript which needs to address all the anynymous types in a JSON object.
For example,
Typed= {
emails: [{email:'a@a.com'}, {email:'b@a.com'}, {email:'c@a.com'}, {email:'d@a.com'}]
};
is an example of typed array in a JSON because each element inside the array is typed email
while,
Anon= {
emails: ['a@a.com', 'b@a.com', 'c@a.com', 'd@a.com']
};
is a JSON object where emails is collection of some anonymous objects.
Is there any ways that I can differentiate between both in JQuery or Javascript?
The simplest solution is to have the JSON source only return one of the two forms. Then you don’t have to branch in your client.
If that’s not an option, you could get the values out with JavaScript’s handy lazy-evaluation of boolean expressions:
That statement will prefer the array-of-objects version, but use the array-of-strings version as a fallback.
(edited in response to clarifying comment below)
You can determine what properties a JS object has at runtime like this:
you could then modulate your logic on the basis of the properties you get back. You’ll want to make sure you understand prototypes (specifically what
Object.hasOwnPropertydoes and means), too.