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 15:06

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;
    });
  };
 }
查看更多
柔情千种
3楼-- · 2019-01-02 15:08

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/

查看更多
与风俱净
4楼-- · 2019-01-02 15:10

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)

查看更多
登录 后发表回答