I have my variable sourceArr, array of objects stored on Window browser scope, and I trying to catch an specific object of this Array making some modifications generating an object through a reducer function, but the problem is when I’m editing the object properties I’m mutating not only my refined_data variable but also the corresponding object on my sourceArr
What is the reason for this behavior? How can I get my refined_data object without mutate my sourceArr?
var dataSeeker = setInterval(() => {
if (window.sourceArr) {
clearInterval(dataSeeker)
let newArr = sourceArr.filter(data => current_case === data.case_id)
let refined_data = newArr.reduce((acc, case_data) => {
case_data.appointment = 'DD/MM/YYYY - hh:mm:ss A'
case_data.name = 'Name'
return case_data
}, {})
}
}, 500)
>Solution :
Your source array is being mutated because your reducer function mutates one of its arguments:
case_data.appointment = ‘DD/MM/YYYY – hh:mm:ss A’
case_data.name = ‘Name’
To prevent it from being mutated, don’t modify the properties of case_data.
For example, do something like
return { appointment: ‘…’, name: ‘…’ };
Also, a useful reducer function should use the content of both its arguments.