Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
how to use .filter to edit a state in react without mutating

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

.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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!