Length of a JavaScript object

2018-12-31 00:25发布

If I have a JavaScript object, say

var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

is there a built-in or accepted best practice way to get the length of this object?

30条回答
闭嘴吧你
2楼-- · 2018-12-31 00:31

If you don't care about supporting Internet Explorer 8 or lower, you can easily get the number of properties in an object by applying the following two steps:

  1. Run either Object.keys() to get an array that contains the names of only those properties that are enumerable or Object.getOwnPropertyNames() if you want to also include the names of properties that are not enumerable.
  2. Get the .length property of that array.

If you need to do this more than once, you could wrap this logic in a function:

function size(obj, enumerablesOnly) {
    return enumerablesOnly === false ?
        Object.getOwnPropertyNames(obj).length :
        Object.keys(obj).length;
}

How to use this particular function:

var myObj = Object.create({}, {
    getFoo: {},
    setFoo: {}
});
myObj.Foo = 12;

var myArr = [1,2,5,4,8,15];

console.log(size(myObj));        // Output : 1
console.log(size(myObj, true));  // Output : 1
console.log(size(myObj, false)); // Output : 3
console.log(size(myArr));        // Output : 6
console.log(size(myArr, true));  // Output : 6
console.log(size(myArr, false)); // Output : 7

See also this Fiddle for a demo.

查看更多
梦寄多情
3楼-- · 2018-12-31 00:31

You can simply use Object.keys(obj).length on any object to get its length. Object.keys returns an array containing all of the object keys (properties) which can come in handy for finding the length of that object using the length of the corresponding array. You can even write a function for this. Let's get creative and write a method for it as well (along with a more convienient getter property):

function objLength(obj)
{
  return Object.keys(obj).length;
}

console.log(objLength({a:1, b:"summit", c:"nonsense"}));

// Works perfectly fine
var obj = new Object();
obj['fish'] = 30;
obj['nullified content'] = null;
console.log(objLength(obj));

// It also works your way, which is creating it using the Object constructor
Object.prototype.getLength = function() {
   return Object.keys(this).length;
}
console.log(obj.getLength());

// You can also write it as a method, which is more efficient as done so above

Object.defineProperty(Object.prototype, "length", {get:function(){
    return Object.keys(this).length;
}});
console.log(obj.length);

// probably the most effictive approach is done so and demonstrated above which sets a getter property called "length" for objects which returns the equivalent value of getLength(this) or this.getLength()

查看更多
余生无你
4楼-- · 2018-12-31 00:32

Here is a completely different solution that will only work in more modern browsers (IE9+, Chrome, Firefox 4+, Opera 11.60+, Safari 5.1+)

See jsFiddle

Setup your Associative Array class

/**
 * @constructor
 */
AssociativeArray = function () {};

// Make the length property work
Object.defineProperty(AssociativeArray.prototype, "length", {
    get: function () {
        var count = 0;
        for (var key in this) {
            if (this.hasOwnProperty(key))
                count++;
        }
        return count;
    }
});

Now you can use this code as follows...

var a1 = new AssociativeArray();
a1["prop1"] = "test";
a1["prop2"] = 1234;
a1["prop3"] = "something else";
alert("Length of array is " + a1.length);
查看更多
若你有天会懂
5楼-- · 2018-12-31 00:33

The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// Get the size of an object
var size = Object.size(myArray);

There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.


Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes:

var size = Object.keys(myObj).length;

This doesn't have to modify any existing prototype since Object.keys() is now built in.

Edit: Objects can have symbolic properties which can not be returned via Object.key method. So the answer would be incomplete without mentioning them.

Symbol type was added to the language to create unique identifiers for object properties. Main benefit of Symbol type is prevention of overwrites.

Object.keys or Object.getOwnPropertyNames does not work for symbolic properties. To return them you need to use Object.getOwnPropertySymbols.

var person = {
  [Symbol('name')]: 'John Doe',
  [Symbol('age')]: 33,
  "occupation": "Programmer"
};

const propOwn = Object.getOwnPropertyNames(person);
console.log(propOwn.length); // 1

let propSymb = Object.getOwnPropertySymbols(person);
console.log(propSymb.length); // 2
查看更多
笑指拈花
6楼-- · 2018-12-31 00:33

To not mess with the prototype or other code, you could build and extend your own object:

function Hash(){
    var length=0;
    this.add = function(key, val){
         if(this[key] == undefined)
         {
           length++;
         }
         this[key]=val;
    }; 
    this.length = function(){
        return length;
    };
}

myArray = new Hash();
myArray.add("lastname", "Simpson");
myArray.add("age", 21);
alert(myArray.length()); // will alert 2

If you always use the add method, the length property will be correct. If you're worried that you or others forget about using it, you could add the property counter which the others have posted to the length method, too.

Of course, you could always overwrite the methods. But even if you do, your code would probably fail noticeably, making it easy to debug. ;)

查看更多
妖精总统
7楼-- · 2018-12-31 00:33

<script>
myObj = {"key1" : "Hello", "key2" : "Goodbye"};
var size = Object.keys(myObj).length;
console.log(size);
</script>

<p id="myObj">The number of <b>keys</b> in <b>myObj</b> are: <script>document.write(size)</script></p>
<p style="font-size:0.6em;">P.S.: If you want to learn Python and have fun go here <a href="https://pythonprogramming.altervista.org/">https://pythonprogramming.altervista.org/</a>
</p>

This works for me:

var size = Object.keys(myObj).length;
查看更多
登录 后发表回答