Jump to content

Distinguish between Array and Object


ShadowMage

Recommended Posts

I have some JSON that will either return a fully populated object:{a: 0, b: 1, c: 2}or an empty array:[] What I'd like to know is, what is the easiest way to distinguish between the two? I know I could do something like: if (obj.a) { or if (obj.length !== undefined) { but these have drawbacks such that:- if the array object happens to have property a, the first if will fail- if the object happens to have a length property, the second one will fail I don't anticipate either of those situations ever happening in this situation because all of the properties are hand written, not dynamically generated. However, I want to know for future reference if there is a better way. Thanks.

Link to comment
Share on other sites

Yeah! I never thought of constructor :facepalm: and didn't even know instanceof existed. I use typeof quite often but that won't work in this situation since arrays are objects. The constructor property and instanceof both work very well. Thanks for the link! :good:

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...