Reputation: 181
I would like to remove one element at index from the list items
inside an array of objects using react.
For now, I do not know which method to use.
const [users, setUsers] = useState([
{
username: "Peter",
items: [
{ name: "Bananas 🍌", quantity: 10 },
{ name: "Strawberry 🍓", quantity: 20 },
{ name: "Milk 🥛", quantity: 6 },
],
},
{
username: "William",
items: [
{ name: "Brocolis 🥦", quantity: 3 },
{ name: "Carottes 🥕", quantity: 10 },
{ name: "Honey 🍯", quantity: 2 },
],
},
]);
// Remove element from list item (Pseudo Code)
function removeItem(index: number) {
const initialState = [...users]
initialState[userIndex].items.splice(itemIndex, 1)
setUsers(initialState)
}
Thank you for your help.
Upvotes: 0
Views: 54
Reputation: 28684
Assuming you want to remove item with index: itemIndex
from user with index userIndex
user.
function removeItem(userIndex, itemIndex) {
return users.map((x, i) => {
if (i === userIndex) return {
...x,
items: x.items.filter((y, j) => j !== itemIndex)
}
return x;
})
}
You have to do it in immutable way since it comes from state.
Upvotes: 1
Reputation: 108
You can use Array.prototype.filter
for that
function removeItem(index: number) {
setUsers(users.filter((user, userIndex) => userIndex !== index))
}
You can read more about Array.prototype.filter
here
Upvotes: 0