I have this object in state below and I would like to filter and return a new state with the selected object removed based on the id that is passed to an onClick.
Object in state:
const [data, setData] = useState({
category1: [
{ category: "category1", id: 1, subcategory: "bob" },
{ category: "category1", id: 2, subcategory: "mike" },
],
category2: [
{ category: "category2", id: 3, name: "swain" },
{ category: "category2", id: 4, name: "teemo" },
{ category: "category2", id: 5, name: "garen" }
]
});
Previously, I was able to remove a whole category itself with onClick with a passed in categoryName as the parameter with this code:
const filteredCategoryData = Object.fromEntries(
Object.entries(data).filter(([key, value]) => key !== category)
);
setData(filteredCategoryData);
Now I want to extend on this logic and loop through the objects of each category and remove the subcategory based on id. I tried:
const filteredsubCategoryData = Object.fromEntries(
Object.entries(data).filter(([key, value]) => {
return value.filter(subCategory => subCategory.id !== id)
});
);
setData(filteredCategoryData);
/* Output -> same original object:
{
category1: [{...}, {...}], category2: [{...}, {...}, {...}]
}
If idToRemove matches first object (index 0) of category1, new object
should return :
category1: [{...}], category2: [{...}, {...}, {...}]
*/
But this filteredsubCategoryData is returning the original intact state and I am confused on why. Thank you for your help!
idof subCategory and what is theidin this expression!== id?