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

190
Visualizações
how to use Immutability helper to update a nested object within an array?

Inside reducer, given a state object:

var state = {
        "data": [{
            "subset": [{
                "id": 1
            }, {
                "id": 2
            }]
        }, {
            "subset": [{
                "id": 10
            }, {
                "id": 11
            }, {
                "id": 12
            }]
        }]
    }

As you can see, the data is a nested array, with arrays in each of its elements.

Knowning that action.indexToUpdate will be a index for data, I want to update data[action.indexToUpdate].subset to a new array programmatically. For example, if action.indexToUpdate = 0, then data[0] will be updated from

[{"id":1},{"id":2}]

to

[{"id":4},{"id":5}]

In order to do so, I have:

let newSubset = [{"id":4},{"id":5}]
let newState = update(state.data[action.indexToUpdate], {
                subset: {
                    newSubset,
                },
            })

But when I executed this, it returns error:

TypeError: value is undefined

on the update founction.

I have been looking at the react ducomentation here: https://facebook.github.io/react/docs/update.html but I couldn't really figure out how to do it. Please advise!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Your update will look like

 var obj = {"state" : {
    "data": [{
        "subset": [{
            "id": 1
        }, {
            "id": 2
        }]
    }, {
        "subset": [{
            "id": 10
        }, {
            "id": 11
        }, {
            "id": 12
        }]
    }]
}}
return update(obj, {
  "state" : {
      "data": {
          [action.indexToUpdate]: {
            "subset": {
                 $set: [newSubset]
            }
          }
      }
  }
})

In case there are other fields in subset, but you only wish to the change the fields at specific index containing other keys, you would write

return update(obj, {
  "state" : {
      "data": {
          [action.indexToUpdate]: {
            "subset": {
                [id]: {$merge: newSubset}
            }
          }
      }
  }
})
over 4 years ago · Santiago Trujillo 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