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:57

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

查看更多
余生请多指教
3楼-- · 2019-01-02 15:00

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();
查看更多
姐姐魅力值爆表
4楼-- · 2019-01-02 15:01

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

len = function(obj) {
    var L=0;
    $.each(obj, function(i, elem) {
        L++;
    });
    return L;
}
查看更多
骚的不知所云
5楼-- · 2019-01-02 15:02

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.

查看更多
梦寄多情
6楼-- · 2019-01-02 15:03

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 ] ]
查看更多
孤独总比滥情好
7楼-- · 2019-01-02 15:04

Can be done easily with $.map():

var len = $.map(a, function(n, i) { return i; }).length;
查看更多
登录 后发表回答