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

143
Visualizações
Update a element inside object in aobject array with Immutability helper js

I need to add or subtract a value of a element in object array using Immutability helper

const selectedFood= [
{id: uuidv4(), name: "pizza", price: 1700, amount: 3},
{id: uuidv4(), name: "cheese", price: 600, amount: 10},
{id: uuidv4(), name: "fried rice", price: 500, amount: 4},
{id: uuidv4(), name: "coke", price: 100, amount: 5}]


const [foodArray, setFoodArray] = useState(selectedFood);

This code works flawlessly and this is what i want except the index

setFoodArray((prev) => {
                 return update(prev, {2: {amount: {$apply: function(x) {return x -1}}}})
        })

the number 2 here should be the index

so i used this to get the index

const index = foodArray.indexOf(foodArray.find((single) => {
            return single.id === id
        }));

putting this index variable there dosn't work

setFoodArray((prev) => {
                 return update(prev, {index: {amount: {$apply: function(x) {return x -1}}}})
        })

Picture for understanding better

can anyone help

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

0

Use bracket notation:

setFoodArray((prev) => {
    return update(prev, {[index]: {amount: {$apply: function(x) {return x -1}}}})
})
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