1

Trying to modify object value in array on condition on some arrays the override does not work, here is my snippet

const removeAction = (target, array, name) => {
        let mutation = JSON.parse(JSON.stringify(array));
        mutation.map( obj => {
            if(obj.value === target.value) {
                console.log(obj)
                obj.checked = false
            } 

            return obj
        })

        console.log(mutation)
        removeCallback(mutation, name)
    }

and I get back the original object in array. How do I debug this issue?

2
  • .map returns a modified copy of the array. You never use that value
    – Cid
    Commented Jan 5, 2021 at 14:03
  • "I get back the original object in array." - where? What does not work? How do you call this, what is removeCallback? Are you passing a target that is not part of the array? Please provide a minimal reproducible example
    – Bergi
    Commented Jan 5, 2021 at 15:17

3 Answers 3

0
const modifiedArray = JSON.parse(JSON.stringify(array)).map(...
0

Map always returns new instance of array. So either assign that mutated map to some variable or loop over and mutate the original array.

0

You could take the mapped objects with destructuring the object and an updated property.

const
    removeAction = (target, array, name) => {
        removeCallback(array.map(obj => ({
            ...obj,
            checked: obj.value === target.value ? false : obj.checked
        })), name)
    };
1
  • Thanks I tried as well I get the same result, It has something to do with Initial array passed to the function
    – fefe
    Commented Jan 5, 2021 at 14:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.