-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

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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!
Ah... yes, you were assuming the functionality of the new for...of loop in ES6 :) developer.mozilla.org/en/JavaScript/Reference/Statements/… Unfortunately, you'll have to wait a while yet to use this.
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.
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

1 Comment

Thanks, but I wasn't asking how to parse.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.