Home > Back-end >  how to use .filter to edit a state in react without mutating
how to use .filter to edit a state in react without mutating

Time:07-05

Im not sure if this is even possible as I dont think .filter can be used for something like this. If I have an array like so:

abc: [
    {number: 1, letter: "a"},
    {number: 2, letter: "b"},
    {number: 3, letter: "c"},
    {number: 4, letter: "d"},
]

I want to do something like this

abc.filter(item => {
        if(item.number == 1){
            
            item.letter == "aa"
        }
    })

Basically updating the first element in the object to be {number:1, letter:"aa"}. However this ends up giving me an empty array. I dont think im going about it in the correct way. How could I use filter to make edits to certain elements?

CodePudding user response:

.filter is not really appropriate here because that would create a new array with only the elements fulfilling the condition, which would then have to be put back into the original array somehow - possible, but convoluted. Map the array instead - if the condition is fulfilled, return a changed object.

Remember that in React, you should avoid mutation - don't assign to a property of an existing object, create a new one instead.

const abc = [
    {number: 1, letter: "a"},
    {number: 2, letter: "b"},
    {number: 3, letter: "c"},
    {number: 4, letter: "d"},
];
const newArr = abc
  .map(obj =>
    obj.number === 1
    ? { ...obj, letter: 'aa' }
    : obj
  );
console.log(newArr);

  • Related