I am working on a function that accepts a JSON object as a parameter. Each property of the object passed in will be an array. I need to determine the length of each of these arrays.
What I won’t know in advance are: the names of the properties, or how many properties there are.
How can I determine the length of each array? Again, I can’t refer to any of the properties/keys explicitly because I won’t know their names ahead of time. How do I reference each unknown property as an array?
Thank you in advance,
-RS
You can iterate over the object using a
for...inloop to access each property.In the above example, we iterate over the properties of the object
myObjectand we log out their length values (assuming they are all arrays).If by “JSON object” you mean that it is a string of JSON, you can first parse myObject into a true object by using
myObject = JSON.parse(myObject)(which works in modern browsers) ormyObject = eval("(" + myOjbect + ")")which is considered unsafe (but works in all browsers). After parsing, you may use the above technique to fine array lengths.Note: Since you updated the post to specify that the object is JSON, you may not need the
hasOwnPropertycheck, but it is safer to always use this test.