SERG SERG - 1 month ago 6
Javascript Question

How to add new property to object?

I have an object

let data = {
"data 1": {
"row1": "aaaa",

},
"data 2": {
"row3": "nnnnn",

}
}


And I want to add some properties with dynamic names and vals to get such an object:

let data = {
"data 1": {
"row1": "aaaa",
"row2": "bbbb",
},
"data 2": {
"row3": "nnnnn",
"row4": "sssss",
"row11": "bbb",
"eeee": "ffff"
},
"dynamic1": {
"dyn_2": "dyn_val_1",
"dyn_3": "dyn_val_2"
}
}


I have tried this code, but it overwrites the data obj with the last value instead of adding

responseJson.results.forEach(function (value) {

data[value.date] = { [value.event_id] : [value.name] };

})

Answer

Well, then don't overwrite the property. Add to the object instead:

responseJson.results.forEach(function (value) {
  if (!data[value.date) {
    data[value.date] = {};
  }
  data[value.date][value.event_id] = value.name;
});

Related: How can I add a key/value pair to a JavaScript object?

Comments