I want to update the object value of shoppingItems
using the es6 spread operator updateObj updates the Object but only inside the function
why does the Object inside shoppingItems does not change its value ?
const kontorGoods = [{ cheese: 5.5 }, { rice: 2.5 }, { meat: 8.8 }];
const shoppingItems = [{ cheese: 5.5 }];
function updateValue(itemIndex){
const item = Object.values(kontorGoods[itemIndex])[0];
updateObj(shoppingItems, itemIndex);
console.log(updateObj(shoppingItems, itemIndex))
}
function updateObj(objArray, objIndex) {
const currentObjkey = Object.keys(objArray[objIndex])[0];
const currentObjValue = Object.values(objArray[objIndex])[0];
return {
...objArray[objIndex],
// add the key as a variable
[currentObjkey]: currentObjValue + currentObjValue,
};
}
updateValue(0)
console.log(shoppingItems)
An object literal creates a new object, it doesn't have any effect at all on the things that you're using to fill in its properties, including any objects you use spread syntax on.
To update the object in the array, write back to the array:
objArray[objIndex] = {
// ^^^^^^^^^^^^^^^^^^^^^
...objArray[objIndex],
// add the key as a variable
[currentObjkey]: currentObjValue + currentObjValue,
};