Basicaly I have an object that has an array in it and I have a superior array of this object.
The object is the following.
category: {
name,
items: [{
id,
name,
price,
image,
}],
}
This array can look like:
[{
name: "Category 1",
items: [{
id: 1,
name: "Item 1 of category 1",
price: 12.34,
image: "/path/to/image",
},
{
id: 2,
name: "Item 2 of category 1",
price: 56.78,
image: "/path/to/image2",
}]
},
{
name: "Category 2",
items: [{
id: 3,
name: "Item 1 of category 2",
price: 87.65,
image: "/path/to/image3",
},
{
id: 4,
name: "Item 2 of category 1",
price: 43.21,
image: "/path/to/image4",
}]
}]
My question is, it's possible to search for the id
since I have an array with all of this data.
Currently I am solving the problem with the following code:
var price = 0;
const menu = [];
state.user.menu.map((item, k) => {
item.category.items.forEach((itm) => menu.push(itm));
return null;
});
state.user.items.forEach((item) => {
price += menu.filter((itm) => itm.id === item.id)[0].price * item.quantity;
});
This basicaly copies every item in the array inside of the object and ignores the category name so I only have a big array.
For what I need now, I need to correlate each item with the category name, so, I can't do as it is now. Basically, I have a list of Ids
and I need to display them with the corresponding category that is in this array.
(Items to search)
[1,3,4]
(Expected Result)
[{
name: "Category 1",
items: [{
id: 1,
name: "Item 1 of category 1",
price: 12.34,
image: "/path/to/image",
}]
},
{
name: "Category 2",
items: [{
id: 3,
name: "Item 1 of category 2",
price: 87.65,
image: "/path/to/image3",
},
{
id: 4,
name: "Item 2 of category 1",
price: 43.21,
image: "/path/to/image4",
}]
}]
Any sugestions is welcome, thanks.
Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW
Comments
Post a Comment