I am trying to concat new items with existing items to an array that is inside the array. This is how my object look like:
{
"categories":[
{
"category":"cat1",
"products":[
{
"prodname":"product1",
"quantity":"10"
},
{
"prodname":"product2",
"quantity":"14"
}
]
},
{
"category":"cat2",
"products":[
{
"prodname":"product3",
"quantity":"11"
},
{
"prodname":"product4",
"quantity":"4"
}
]
}
]
}
This is how I update the products array when I get new products in an array for a category.
var indexOfCategory = categoryDataCache.categories.findIndex(c => c.category === "cat1");
setCategoryDataCache(prevState => ({
...prevState,
categories: [{
[indexOfCategory]: {
products: prevState.categories[indexOfCategory].products.concat(newproducts)
}
}]
}))
here are the 2 problems with this code:
- it overrides the existing category object as I do not see
quantityproperty after the update - It adds new products as array of products array instead of concatenating the existing products array.
What am I missing here?