Javascript setter for value of object

218 Views Asked by At

I have created a "set" function to which it will trigger during the value change of my object "myObject.user". So when i am changing the value i am getting alert. but when i am updating the value inside the object "myObject.newuser[0].id" the set is not calling. How to change the code such that if any inner value is changed the global set should work. ie for this code i should get two alert.

var myObject = {};
myObject.user;
 
Object.defineProperty(myObject, 'newuser', {
     get: function() { return this.user;},
     set: function(value) { alert('Updated');this.user=value;}
});
 
myObject.newuser = [{"id":"user1"}];
myObject.newuser[0].id="user2";

1

There are 1 best solutions below

0
On

Well you need to change the property myObject.newuser[0].id to myObject.user[0].id then it will set the new value to existing user's value.

Because you changing the previously added value with new value.

Please refer to MDN link for more details on setter.