How to get object length

JavascriptJsonObject

Javascript Problem Overview


Is there any built-in function that can return the length of an object?

For example, I have a = { 'a':1,'b':2,'c':3 } which should return 3. If I use a.length it returns undefined.

It could be a simple loop function, but I'd like to know if there's a built-in function?

There is a related question (Length of a JSON object) - in the chosen answer the user advises to transform object into an array, which is not pretty comfortable for my task.

Javascript Solutions


Solution 1 - Javascript

For browsers supporting Object.keys() you can simply do:

Object.keys(a).length;

Otherwise (notably in IE < 9), you can loop through the object yourself with a for (x in y) loop:

var count = 0;
var i;

for (i in a) {
    if (a.hasOwnProperty(i)) {
        count++;
    }
}

The hasOwnProperty is there to make sure that you're only counting properties from the object literal, and not properties it "inherits" from its prototype.

Solution 2 - Javascript

This should do it:

Object.keys(a).length

However, Object.keys is not supported in IE8 and below, Opera and FF 3.6 and below.

Live demo: http://jsfiddle.net/simevidas/nN84h/

Solution 3 - Javascript

Can be done easily with $.map():

var len = $.map(a, function(n, i) { return i; }).length;

Solution 4 - Javascript

Have you taken a look at underscore.js (http://underscorejs.org/docs/underscore.html)? It's a utility library with a lot of useful methods. There is a collection size method, as well as a toArray method, which may get you what you need.

_.size({one : 1, two : 2, three : 3});
=> 3

Solution 5 - Javascript

Summarizing all together, here is a universal function (including ie8 support):

var objSize = function(obj) {
    var count = 0;
    
    if (typeof obj == "object") {
    
        if (Object.keys) {
            count = Object.keys(obj).length;
        } else if (window._) {
            count = _.keys(obj).length;
        } else if (window.$) {
            count = $.map(obj, function() { return 1; }).length;
        } else {
            for (var key in obj) if (obj.hasOwnProperty(key)) count++;
        }
        
    }
    
    return count;
};

document.write(objSize({ a: 1, b: 2, c: 3 }));
// 3

Solution 6 - Javascript

In jQuery i've made it in a such way:

len = function(obj) {
	var L=0;
	$.each(obj, function(i, elem) {
		L++;
	});
	return L;
}

Solution 7 - Javascript

So one does not have to find and replace the Object.keys method, another approach would be this code early in the execution of the script:

if(!Object.keys)
{
  Object.keys = function(obj)
  {
    return $.map(obj, function(v, k)
    {
      return k;
    });
  };
 }

Solution 8 - Javascript

Here's a jQuery-ised function of Innuendo's answer, ready for use.

$.extend({
    keyCount : function(o) {
        if(typeof o == "object") {
            var i, count = 0;
            for(i in o) {
                if(o.hasOwnProperty(i)) {
                    count++;
                }
            }
            return count;
        } else {
            return false;
        }
    }
});

Can be called like this:

var cnt = $.keyCount({"foo" : "bar"}); //cnt = 1;

Solution 9 - Javascript

Also can be done in this way:

Object.entries(obj).length

For example:

let obj = { a: 1, b: 2, };
console.log(Object.entries(obj).length); //=> 2
// Object.entries(obj) => [ [ 'a', 1 ], [ 'b', 2 ] ]

Solution 10 - Javascript

One more answer:

var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]';

obj = Object.keys(j).length;
console.log(obj)

Solution 11 - Javascript

For those coming here to find the item count of something that is already a jQuery object:
.length is what you are looking for:

Example:

len = $('#divID').length;
alert(len);

Solution 12 - Javascript

If you want to avoid new dependencies you could make your own smart objects. Of course only if you want to do more that just get it's size.

MyNeatObj = function (obj) {
  var length = null;

  this.size = function () {
    if (length === null) {
      length = 0;
      for (var key in obj) length++;
    }
    return length;
  }
}

var thingy = new MyNeatObj(originalObj);
thingy.size();

Solution 13 - Javascript

You might have an undefined property in the object. If using the method of Object.keys(data).length is used those properties will also be counted.

You might want to filter them out out.

Object.keys(data).filter((v) => {return data[v] !== undefined}).length

Solution 14 - Javascript

You may use something like Lodash lib and _.toLength(object) should give you the length of your object

Solution 15 - Javascript

You could add another name:value pair of length, and increment/decrement it appropriately. This way, when you need to query the length, you don't have to iterate through the entire objects properties every time, and you don't have to rely on a specific browser or library. It all depends on your goal, of course.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLarry CinnabarView Question on Stackoverflow
Solution 1 - JavascriptDavid TangView Answer on Stackoverflow
Solution 2 - JavascriptŠime VidasView Answer on Stackoverflow
Solution 3 - JavascriptFazle RabbiView Answer on Stackoverflow
Solution 4 - JavascriptPhilip SchweigerView Answer on Stackoverflow
Solution 5 - JavascripttibaltView Answer on Stackoverflow
Solution 6 - JavascriptLarry CinnabarView Answer on Stackoverflow
Solution 7 - JavascriptRobert BrisitaView Answer on Stackoverflow
Solution 8 - JavascriptAndrew PlankView Answer on Stackoverflow
Solution 9 - Javascriptsulthan thoufeeqView Answer on Stackoverflow
Solution 10 - JavascriptMahendra KulkarniView Answer on Stackoverflow
Solution 11 - JavascriptJpsyView Answer on Stackoverflow
Solution 12 - JavascriptdoublejoshView Answer on Stackoverflow
Solution 13 - JavascriptYaki KleinView Answer on Stackoverflow
Solution 14 - JavascriptHamatekView Answer on Stackoverflow
Solution 15 - Javascriptajq88View Answer on Stackoverflow