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.
Distinguish between Array and Object
Started by ShadowMage, Mar 29 2012 04:50 PM
2 replies to this topic
#1
Posted 29 March 2012 - 04:50 PM
In programming, failure is not an option. It's an inevitability...
Mosher's Law of Software Engineering: "Don't worry if it doesn't work right. If everything did, you'd be out of a job."
Call upon the FireBug and its swarm!
Darkness Falls - W3Schools Forum skin for Stylish
Mosher's Law of Software Engineering: "Don't worry if it doesn't work right. If everything did, you'd be out of a job."
Call upon the FireBug and its swarm!
Darkness Falls - W3Schools Forum skin for Stylish
#2
Posted 29 March 2012 - 05:26 PM
http://stackoverflow...ash-or-an-array
seems like an option.
seems like an option.
Edited by thescientist, 29 March 2012 - 05:40 PM.
myTunes: www.analogstudios.net
SirCharlo, on May 13 2011, 03:03 PM, said:
my {...} code {...} works in all the decent browsers. This of course means that it does not work in IE.
#3
Posted 29 March 2012 - 06:30 PM
Yeah! I never thought of constructor
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!
Thanks for the link!
In programming, failure is not an option. It's an inevitability...
Mosher's Law of Software Engineering: "Don't worry if it doesn't work right. If everything did, you'd be out of a job."
Call upon the FireBug and its swarm!
Darkness Falls - W3Schools Forum skin for Stylish
Mosher's Law of Software Engineering: "Don't worry if it doesn't work right. If everything did, you'd be out of a job."
Call upon the FireBug and its swarm!
Darkness Falls - W3Schools Forum skin for Stylish
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users












