简体   繁体   中英

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

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM