Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 908
Sachin Shanbhag Avatar asked Aug 20 '10 09:08

Sachin Shanbhag


People also ask

How do you find the number of elements in an object?

To get the number of elements in a JavaScript object, we can use the Object. keys method. const count = Object. keys(obj).

Which function returns the number of the elements in the object?

Using count() Function: The count() function is used to get the total number of elements in an array.

What's the attribute to get the number of of items stored in a set object?

The size accessor property returns the number of (unique) elements in a Set object.


1 Answers

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

like image 188
Kristoffer Sall-Storgaard Avatar answered Oct 30 '22 09:10

Kristoffer Sall-Storgaard