Javascript automatically adds property when expanding an object

When working with JavaScript, I came across a situation where I am not sure that what I'm trying to do is possible:

Given the following object:

var data = {}; 

Is it possible to change the "data" so that when it is expanded as follows:

 data.entry_1 = { 'prop_1': 'set_1', 'prop_2': 'set_2' }; 

the new property is automatically bound to the new object, i.e.

 data.entry_1 = { 'prop_1': 'set_1', 'prop_2': 'set_2', id: 1 // automatically created property }; 

Is it possible to do the above without using "external" methods, for example. no data.newEntry (object)?

+4
source share
1 answer
 var data = { set entry_1 (val) { for(var i in val) { this[i] = val[i] }; this["id"] = 1; } } 

Supported in IE9 + and other modern browsers.

+1
source

All Articles