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

196
Visualizações
How to update and target the right index in an array which is nested in an object?

I have the following react state, I want to update the second value not the whole object and I don't want to use an object as a value either, for now I can only change the whole object but not the specific wanted value how to target and update the wanted index.

// State 
const [state, setState] = useState({
    element: [false, 'starter text']
 });
  
// Update State logic
 setState({ ...state, element: [(element[1] = 'updated text')] });

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

0

When updating state in React you shallow copy the state, and nested state, that you are updating. For arrays this means you shallow copy the array.

// State 
const [state, setState] = useState({
  element: [false, 'starter text']
});
  
// Update State logic
setState(state => ({
  // shallow copy any previous root-level state
  ...state,

  // shallow copy the previous state's element array
  // when the mapped index matches the index you want to update
  // return the updated value, otherwise return existing value
  element: state.element.map((el, i) => i === 1 ? 'updated text' : el)
}));

If the array was an array of objects then you need to shallow copy them as well, then update the nested property.

Example:

element: state.element.map(
  (el, i) => i === 1
    ? {
      ...el,
      nestedProperty: 'updated text'
    }
    : el
)

I know this Immutable Update Patterns doc is from Redux, but is solves many common React state update issues.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can create a new state state as codeSandbox

   setState(oldState => {
     const newState = { ...oldState, element: [ ...oldState.element ]};
     newState.element[1] = "updated text";
     return newState;
   })
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use Object.assign. Since an array is an Object with indices as its properties, you can do this:

const arr = [1, 2, 3, 4, 5];
const updatedArr = Object.assign([], arr, { 1: 10 }); // Update value at index 1.

console.log(arr);
console.log(updatedArr);

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