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

135
Vistas
Conditionally add to array of objects using spread operator

I would like to conditionally add something to an array using a spread operator if it matches a particular condition (ie. if the movie id does not match other movie id's that already exist in my array)

case ADD_FAVORITE:
    return {
            ...state,
            favorites: [ state.favorites !== action.payload.id? ...state.favorites, action.payload]
    }

This is what I have tried

action payload returns something like this

{id: 0, title: 'The Godfather', director: 'Francis Ford Coppola', metascore: 100, genre: 'Drama', …}

and inside state.favorites:

description: "Luke Skywalker joins forces with a Jedi Knight, a cocky pilot, a Wookiee and two droids to save the galaxy from the Empire's world-destroying battle station, while also attempting to rescue Princess Leia from the mysterious Darth Vader."
director: "George Lucas"
genre: "Scifi"
id: 1
metascore: 92
title: "Star Wars"
[[Prototype]]: Object
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I'd do the check before the return, since you don't need to update state at all if nothing changes:

case ADD_FAVORITE:
    if (state.favorites.some(({id}) => id === action.payload.id)) {
        // It's already there, we don't need to modify state at all
        return state;
    }
    return {...state, favorites: [...state.favorites, action.payload]};

If you want to update state even though nothing changes, just do that in the branch:

case ADD_FAVORITE:
    if (state.favorites.some(({id}) => id === action.payload.id)) {
        // It's already there, we don't need to modify state at all
        return {...state};
    }
    return {...state, favorites: [...state.favorites, action.payload]};

or

case ADD_FAVORITE:
    let favorites = state.favorites;
    if (!favorites.some(({id}) => id === action.payload.id)) {
        // Don't have it, add it
        favorites = [...favorites, action.payload];
    }
    return {...state, favorites};

(Again, if you want to return a new state object even when nothing changes.)

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