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

164
Visualizações
Finding changes between two lists of objects in javascript using React state

I'm trying to figure out how to differentiate additions and/or deletions between two lists (based on a starting list) in Javascript. For example,

var AllPossibleThings = [
{key: '1', value: 'thing 1'},
{key: '2', value: 'thing 2'}, 
{key: '3', value: 'thing 3'}, 
{key: '4', value: 'thing 4'}, 
{key: '5', value: 'thing 5'}, 
{key: '6', value: 'thing 6'}, 
{key: '7', value: 'thing 7'}
]

var serverStateOfThings = [
 {key: '2', value: 'thing 2'}, 
 {key: '3', value: 'thing 3'}
]

var newStateOfThings = [
 {key: '1', value: 'thing 1'}, 
 {key: '4', value: 'thing 4'}
]

At this moment the server cache of a particular entity is that it references thing 2 and thing 3. After some client-side operations, I have new state that I need to persist to the server. But I want to separate the state into add and delete operations.

Using the above example I want the result to be:

const newStateOfThingsWithExtra = [
{key: '1', value: 'thing 1', op: "add"}, 
{key: '4', value: 'thing 4', op: "add"}, 
{key: '1', value: 'thing 1', op: "delete"}, 
{key: '3', value: 'thing 3', op: "delete"},]

So I can then go:

const toDelete = newStateOfThingsWithExtra.filter(i => i.op === 'delete');
const toAdd = newStateOfThingsWithExtra.filter(i => i.op === 'add');

And make two calls to the server, one for the deletes and one for the additions. Something like:

async function SaveThings() {
  return await axios.delete(myUrl, toDelete)
    .then(response => {
       axios.post(myUrl, toAdd) 
   })
}  

For context, I'm using an assignment list component and passing:

<AssignmentList leftSide={AllPossibleThings} rightSide={serverStateOfThings} />

There's an onChange that passes you back the current right side each time the user adds or removes from the list. Then I need to handle the saving.

I'm having trouble wrapping my head around the logic more than I am the syntax. I can easily check one list against another to see if it's there or not. But if it is, how do I know if something was there and now isn't, and if something isn't there now but was... by referencing a third list?

about 4 years ago · Juan Pablo Isaza
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