简体   繁体   中英

Remove a property from an immutable JS object

In my react-native application, I want to remove a property of my js object which is in redux.

here is my code.

    case SAVE_PLAYLIST:
        const { toPlayListFrom, selectedPlaylist } = action.payload;

        let newPlaylists = // state.savedPlaylists;
            Object.keys(selectedPlaylist).length > 0
                ?  {
                    ...state.savedPlaylists,
                    [toPlayListFrom]: selectedPlaylist
                }
                : delete state.savedPlaylists[toPlayListFrom];

        return {
            ...state,
            savedPlaylists: newPlaylists
        }

in this line, delete state.savedPlaylists[toPlayListFrom] it doesn't remove the property as expected. How can I delete a property from an immutable js object in a right way?

Your delete statement is wrong. The command generally returns true (in a few cases it may return false.)

Also, as mentioned by TJ Crowder, you do not want to modify the state variable.

First you want to create a copy of the data and then apply a delete on the copy.

case SAVE_PLAYLIST:
    const { toPlayListFrom, selectedPlaylist } = action.payload;

    let newPlaylists = // state.savedPlaylists;
        Object.keys(selectedPlaylist).length > 0
            ?  {
                ...state.savedPlaylists,
                [toPlayListFrom]: selectedPlaylist
            }
            : ...state.savedPlaylists;

    // only apply a delete to the copy, not the original
    //
    if (Object.keys(selectedPlaylist).length === 0) {
        delete newPlaylists.savedPlaylists[toPlayListFrom]
    }

    return {
        ...state,
        savedPlaylists: newPlaylists
    }

One thing to keep in mind in JavaScript is that objects use references. So if you don't first make a copy, you are changing said object (or attempting to, at least, some objects could be marked immutable ( const , really) and thus can't be modified.)

I'm sure there are ways to optimize the above code.

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