My array is like so:
let dup= [
{
"category": "snacks",
"id": 1,
"data": [
{
"id": 11,
"title": "choclate",
"subItem": [],
"count": 0
},
{
"id": 1,
"title": "Protein Bar",
"subItem": [],
"count": 0
}
]
},
{
"category": "beverages",
"id": 2,
"data": [
{
"id": 2,
"title": "Tea",
"subItem": [
{
"id": 1,
"title": "sugar",
"status": 1,
"createdAt": "2021-11-10T03:35:02.500Z",
"updatedAt": "2021-11-10T03:35:02.500Z"
}
],
"count": 0
},
{
"id": 3,
"title": "Coffee",
"subItem": [
{
"id": 1,
"title": "sugar",
"status": 1,
"createdAt": "2021-11-10T03:35:02.500Z",
"updatedAt": "2021-11-10T03:35:02.500Z"
}
],
"count": 0
}
]
}
]
I was trying to change the count (just like a shopping cart)
I tried to solve the problem by the function above, but i am not getting the required result. The array is not getting changed.
function getNewCartItems() {
let newvar= dup.map(element => (element = element.data.map(item => (item.id === action.item.id ? {...item, count: item.count 1} : item))));
return newvar;
}
CodePudding user response:
map
will return a new array with the changes made by the callback. You want to return that array. Easiest thing to do would be declare it as a variable and return it:
const newCart = dup.map(...)
return newCart
CodePudding user response:
Solved by the following:
function getNewCartItems() {
const newArr = state.data?.map(element => {
return {
...element,
data: element?.data?.map(item => (item.id === action.item.id ? {...item, count: item.count 1} : item)),
};
});
return newArr;
}