Sachin Shanbhag
Sachin Shanbhag

Reputation: 55489

Is there a way to get number of elements from object?

Let me explain in detail. I have below an object with me -

{
    "OBJECT1" : {
        "NAME1" : "VALUE1",
        "NAME2" : "VALUE2",
        "NAME3" : "VALUE3"
     },
     "OBJECT2" : {
        "NAME4" : "VALUE4",
        "NAME5" : "VALUE5"
     }
}

From this object, I want to get something like number of elements in OBJECT1 = 3 and number of elements in OBJECT2 = 2. If at all this is possible using javascript. Basically what I am trying to do is, to loop through the name value pairs available in the object dynamically so that if someone adds another element to object, I don't have to change my code.

Also any alternative is also ruled out since I am allowed to only use object in my use-case.

Upvotes: 7

Views: 7287

Answers (3)

Kristoffer Sall-Storgaard
Kristoffer Sall-Storgaard

Reputation: 10636

Without converting your object you could iterate through the object counting properties like so:

function countObjectProperties(obj)
{
    var count = 0;
    for(var i in obj)
        if(obj.hasOwnProperty(i))
            count++;

    return count;
}

Expanding on why you need to use hasOwnProperty as I said in the comment below you can run into an issue where a library or browser has added methods and properties to Objects, in order to avoid counting these we check for hasOwnProperty before counting it. More details at MSDN or at Mozilla Developer Center

Upvotes: 9

KeatsPeeks
KeatsPeeks

Reputation: 19327

For JSON string that represent an object (which is your case), you cannot use any length property. you need to loop through the object (see Kristoffer S Hansen's answer).

If it represented an array, you could get the length with:

var len = arr.length;

JQuery makes it simpler:

var len = $(JSON).length;

Upvotes: 4

Piskvor left the building
Piskvor left the building

Reputation: 92752

To answer your broader goal, as specified in your question:

For looping through the properties, you can use the for..in construct:

for (var item in myobject) {
  // some browsers add more properties to every object, we don't want those
  if (myobject.hasOwnProperty(item)) {
    do_something(item);
  }
}

Assuming that myobject is the object in your question, this will loop through it and call do_something(OBJECT1) and do_something(OBJECT2); you can use the same construct to loop through the child objects:

// loop through OBJECT1 and OBJECT2
for (var item in myobject) {
  // some browsers add more properties to every object, we don't want those
  if (myobject.hasOwnProperty(item)) {
    // loop through the item's children
    for (var pair in item) {
      if (item.hasOwnProperty(pair)) {
        // each of the name:value pairs will be passed to this
        do_something_else(item,pair);
      }
    }
  }
}

Upvotes: 1

Related Questions