I'm tired of looping through an object literal to get its length for one reason or another. I want to define a length
property onto Object.prototype
, I can set the initial length, but I don't know how to update it when the object is modified?
var obj = {a:1, b:2, c:3};
Object.defineProperty(Object.prototype, 'length', {value: 0});
// obj.length === 0;
obj.d = 4;
// obj === {a:1, b:2, c:3, d:4};
// obj.length === 0;
Any String/Array object does this automatically, if you know how this happens then please enlighten me, if not then maybe you know a way to update this custom property?
If you want the length of the number of keys in an object, use
Object.keys(obj).length
.If you're crazy and want it on the prototype...
These are host objects/primitives and it happens behind the covers.