Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
Can I update an array of objects by modifiying a value return by array.find()?

I want to modify an object in an array by calling array.find() and then mutate the returned reference to indirectly mutate the array but that doesnt appear to work. I assumed from reading other articles that array.find() returns a reference to an object in the array on a successful match but that appears not the be the case.

In this codesandbox if I mutate the result from array.find() the array is not updated. I can update the array if I replace array.find() with array.findIndex() and modify the array elements by index, but the code is not as clean and I still dont understand why I cant update by reference.

Does array.find() return a reference to an object in the array or a copy? In the codesandbox provided it appears to behave as though its a copy.

Any advice is appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Find just finds the first element in the array, they do not edit the element, but find the element. So when you have the element, you can edit afterward, but you do not have the index of the element inside the array, so you will need the index too if you want to pass the edited element in the array.

You have multiple ways to update. If you want a shorter way, right now it came into my mind like this :

   setArray((oldState) =>
      oldState.map((item) => {
        if (item.value === "one") {
          return {
            value: "asdasd"
          };
        }
        return {...item};
      })
    );

So directly you can set the value inside setArray why? because the map returns a new array. Or you can write more readable :

 const newState = array.map((item) => {
        if (item.value === "one") {
          return {
            value: "asdasd"
          };
        }
        return {...item};
      });
    setArray(newState)

A similar question can be found here

If you have any questions ask. Thanks.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda