Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!