While I understand this is a rather common question, my search through various sources has yielded answers that involve libraries, ES6, or methods not supported by native JavaScript. My goal is to simply replace one object with another based on a condition - no ES6, no clone
, and no copy
.
In the scenario below: I aim to extract values from subObj
and replace them with the values in Obj1
For example, I want attributes "key2" and "key3" to be replaced with the values present in subObj.
Obj1 = {
"key1" : {values:[1, 2, 44, 505]},
"key2" : {values:[91, 25, 44, 5995]},
"key3" : {values:[1, 24, 44, 595]},
"key4" : {values:[17, 28, 44, 559]}
}
subObj = {
**"key2" : {values:[3, 3, 3, 444]},** // add this one
**"key3" : {values:[1, 0, 0, 0]}**
}
The desired output should look like:
Obj1 = {
"key1" : {values:[1, 2, 44, 505]},
**"key2" :{ values:[3, 3, 3, 444]},**
**"key3" : {values:[1, 0, 0, 0]},**
"key4" : {values:[17, 28, 44, 559]}
}
Thus far, I have attempted the following code snippet:
somefunc: function(condition) {
if (condition) {
Object.keys(Obj1).forEach(function(key) { Obj[key] = Obj1[key]});
return Obj1;
}
return Obj;
},
However, this method has not produced the expected results. Any assistance would be greatly appreciated. Thank you!