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

108
Visualizações
update Object value globally

I want to update the object value of shoppingItems
using the es6 spread operator updateObj updates the Object but only inside the function
why does the Object inside shoppingItems does not change its value ?

const kontorGoods = [{ cheese: 5.5 }, { rice: 2.5 }, { meat: 8.8 }];
const shoppingItems = [{ cheese: 5.5 }];


function updateValue(itemIndex){
    const item = Object.values(kontorGoods[itemIndex])[0];
    updateObj(shoppingItems, itemIndex);
    console.log(updateObj(shoppingItems, itemIndex))
}


function updateObj(objArray, objIndex) {
    const currentObjkey = Object.keys(objArray[objIndex])[0];
    const currentObjValue = Object.values(objArray[objIndex])[0];
  
    return {
      ...objArray[objIndex],
      // add the key as a variable
      [currentObjkey]: currentObjValue + currentObjValue,
    };
  }

updateValue(0)
console.log(shoppingItems)

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

0

An object literal creates a new object, it doesn't have any effect at all on the things that you're using to fill in its properties, including any objects you use spread syntax on.

To update the object in the array, write back to the array:

    objArray[objIndex] = {
//  ^^^^^^^^^^^^^^^^^^^^^
      ...objArray[objIndex],
      // add the key as a variable
      [currentObjkey]: currentObjValue + currentObjValue,
    };
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