I have nested object, and on incoming change I want to create copy of expenses object and update all timeSpent values. New values are calculated from updated data, so I have to make the calculation for every timeSpent value. I can't find a way to do this.
I have tired creating copy of expenses object using {...expenses.byId} and making array from it with Ovject.values, mapping the data and making calculations. Then problem arises, values are nested, so original object gets changed.
I have tired to make a deep copy of the object, the problem is the same or I'm doing something wrong. If I need to go one level deeper in copyOfExpenses how should I do that?
const state = {
expenses: {
byId: {
k948zpnp: {
id: 'k948zpnp',
category: 'other',
description: 'book',
amount: '25',
timeSpent: '2.5',
time: '2020-4-21 10:48:10'
},
z9e8ipnp: {
id: 'z9e8ipnp',
category: 'food',
description: 'pasta',
amount: '12',
timeSpent: '1.2',
time: '2020-4-21 11:48:10'
},
},
allIds: ['k948zpnp', 'z9e8ipnp']
}
}
const copyOfExpenses = {
...state,
expenses: {
...state.expenses,
byId: { ...state.expenses.byId },
allIds: [...state.expenses.allIds]
}
}
let newInputForTimeSpent = 14
let newData = copyOfExpenses.expenses.allIds.map(
item =>
(copyOfExpenses.expenses.byId[item].timeSpent =
copyOfExpenses.expenses.byId[item].timeSpent * newInputForTimeSpent)
)
console.log(copyOfExpenses) // changes works
console.log(state) // original data gets changed