I've come across an interesting anomaly with Object.assign in the following scenario.
function sampleFunction(index, myList) {
myList.forEach((element, i) => {
if (i === index) {
console.log(Object.assign({}, {"newKey": "newValue"}, element));
return Object.assign({}, {"newKey": "newValue"}, element);
}
});
}
console.log(sampleFunction(0, [{"key1": "value1", "key2": "value2"}]));
The output is
{
"newKey": "newValue",
"key1": "value1",
"key2": "value2"
}
undefined
Instead of
{
"newKey": "newValue",
"key1": "value1",
"key2": "value2"
}
{
"newKey": "newValue",
"key1": "value1",
"key2": "value2"
}
When the forEach loop is replaced with a for loop, the output is as expected.
function updatedFunction(index, myList) {
for(let i = 0; i < myList.length; i++){
let element = myList[i];
if (i === index) {
console.log(Object.assign({}, {"newKey": "newValue"}, element));
return Object.assign({}, {"newKey": "newValue"}, element);
}
}
}
console.log(updatedFunction(0, [{"key1": "value1", "key2": "value2"}]));
Can anyone shed some light on this issue?