Updating Custom Object Properties in JavaScript

570 views Asked by At

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?

3

There are 3 answers

1
alex On

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...

Object.prototype.getKeyLength = function() {
    return Object.keys(this).length;
};

Any String/Array object does this automatically, if you know how this happens then please enlighten me...

These are host objects/primitives and it happens behind the covers.

5
DMaster On

You can try this:

Object.defineProperty(Object.prototype, 'keylength', {
  get: function getKeyLength() {
    return Object.keys(this).length;
  }
});
0
fuyushimoya On

Your init guess is close enough, from Object.defineProperty()

You can use use get instead of value, to define a getter, which be called when the defined property is accessed.

A Demo

Object.defineProperty(Object.prototype, 'len', {
  writeable: false,
  get: function() {
    return Object.keys(this).length;
  }
});

var a = {
  't' : 'This',
  's' : 'A tsets'
};

console.log(a.len);

a['2222'] = 3;

console.log(a.len);