How to get object length

2019-01-02 14:08发布

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.

15条回答
何处买醉
2楼-- · 2019-01-02 14:44

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
查看更多
心情的温度
3楼-- · 2019-01-02 14:47

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
查看更多
若你有天会懂
4楼-- · 2019-01-02 14:52

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.

查看更多
与君花间醉酒
5楼-- · 2019-01-02 14:54

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

查看更多
浮光初槿花落
6楼-- · 2019-01-02 14:56

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);
查看更多
浪荡孟婆
7楼-- · 2019-01-02 14:57

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;
查看更多
登录 后发表回答