in

How to prevent duplication of of an object by array.reduce function


I have the following function:

    range: [number, number] = [135, 145]

    update(property: string, path: string, range: [number, number]) {   
            if (path.split('|').length === 2) {
                const steps = path.split('|')
                
                const addressSteps = steps.slice(0, -1)

                const lastStep = addressSteps[addressSteps.length - 1]
            
                const reducer = (accu, step) => accu[step]

                // We get to the branch you need to update
                const stateBranch = addressSteps.reduce(reducer, state)

                stateBranch[lastStep] = {
                    ...stateBranch[lastStep],
                    [property]: range,
                }

        }),
    )
}

Invoking the fuction…

update(bHbMaleMass, 'haematology|cbc', [135, 145])

…update the state as shown in the screen capture

Note the following:

  1. the haematology node is INCORRECTLY duplicated in the cbc node with the correct updated data.

What I am trying to accomplish is to update the cbc node ONLY – there should be no duplicate of the haematology or cbc nodes.

Thanks for the help

NB previously posted at [Looking for a better way to structure code closed which was closed. The question relates to one of the solutions offered in the response.



Source: https://stackoverflow.com/questions/70601956/how-to-prevent-duplication-of-of-an-object-by-array-reduce-function

Backup Folder Undefined in Google Apps Script

React markdown editor with preview