Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

60
Views
Remove value from an array nested in an object

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.

7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

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

7 months ago · Juan Pablo Isaza Report

0

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)};
})
7 months 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 job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.