-1

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

RLS
  • 1
  • 3
  • possible duplicate of [How to get an object's properties in JavaScript / jQuery?](http://stackoverflow.com/questions/4079274/how-to-get-an-objects-properties-in-javascript-jquery) – Felix Kling Jun 22 '12 at 16:33
  • You can get the length of an array from its `length` property. – Felix Kling Jun 22 '12 at 16:33

2 Answers2

0

Use JSON.parse to convert JSON data to JS Objects, and then you can use Array's length etc properties.

var myObject = JSON.parse(myJSONtext, reviver);

JSON Reference: http://www.json.org/js.html

Hrishikesh
  • 1,076
  • 1
  • 8
  • 22
0

You can iterate over the object using a for...in loop to access each property.

for (var key in myObject) {
  // Check to make sure the property is not part of the `Object` prototype (eg. toString)
  if (myObject.hasOwnProperty(key)) {
    console.log(key, myObject[key].length);
  }
}

In the above example, we iterate over the properties of the object myObject and 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) or myObject = 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 hasOwnProperty check, but it is safer to always use this test.

Jacob Swartwood
  • 4,075
  • 1
  • 16
  • 17
  • Action Jake: Thank you. This is the approach I was using, but now I see what I was missing. I'll use your variable names to illustrate: I was trying to reference the arrays in the for...in loop using myObject instead of myObject[key]. Therefore, myObject.length simply returned the length of the String containing the key's name. Thank you! – RLS Jun 22 '12 at 17:02
  • Ah... yes, you were assuming the functionality of the new `for...of` loop in ES6 :) https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...of Unfortunately, you'll have to wait a while yet to use this. – Jacob Swartwood Jun 22 '12 at 17:25
  • Correction": I was trying to reference the arrays in the for...in loop using key instead of myObject[key]. Therefore, key.length simply returned the length of the String containing the key's name. – RLS Jun 22 '12 at 17:36