Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the origin array of my reducer function are being mutated?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading