Home > Net >  Remove value from an array nested in an object
Remove value from an array nested in an object

Time:03-17

I have a problem with my code. I currently have some data like the one below;

 users: [
    {
      name: 'bolu',
      features: ['Tall'],
    },
    {
      name: 'cam',
      features: ['Bearded', 'Short'],
    },
  ],
};

What I am trying to do is delete/remove a single feature - for example if I pass in 'short' into my redux action. I'd like for it (the 'Short' text) to be removed from the features array. I currently have my redux action set up this way:

export interface UsersDataState {
  name: string,
  features: Array<string>,
}

export interface UsersState {
  users: UsersDataState[];
}

const initialState: UsersState = {
  users: [],
};

    export const usersSlice = createSlice({
      name: 'users',
      initialState,
      reducers: {
        removeUser: (state, action: PayloadAction<string>) => {
          const removedUsers = state.users.filter((user) => user.features.indexOf(action.payload));
          state.users = removedUsers;
        },
       },
   });

So here I am passing in the value in (action.payload is the value being passed in). When this action is dispatched, I want to remove just the word that is passed in from the features array. I hope this is clearer now.

This doesn't work for some reason and I am unable to figure out why. Any help would be appreciated please, thank you.

CodePudding user response:

You need to copy the objects on users and filter on features.

Here an example:

var users = [{
  name: 'bolu',
  features: ['Tall'],
}, {
  name: 'cam',
  features: ['Bearded', 'Short'],
}];

const payload = "Short";

const newUsers = users.map(user => ({ ...user,
  features: user.features.filter(f => f != payload)
}));

console.log(newUsers);

CodePudding user response:

Currently you are filtering users array but you should be filtering nested features array.

Try this

const removedUsers = state.users.map(user => {
  return {...user, features: user.features.filter(feature => feature !== action.payload)};
})
  • Related