Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda