【发布时间】:2021-07-25 06:11:48
【问题描述】:
我正在制作一个送餐应用,我有两个不同的对象数组。其中一个是cartItems,另一个是foodItems。数组可以有不同的大小。那么我想遍历每个数组并检查什么
-
如果两个数组的 id 匹配。
-
Note我想检查数量是否存在,然后将其增加新数量,否则只需添加新数量 -
检查
foodItems数组中是否存在itemDetails,如果存在,检查cartItems的price是否与该foodItem匹配,然后更新cartItems对象,否则将其删除。 -
如果 itemDetails 不存在,则更新项目的数量。
更新 如果有两个id和价格相似的商品,应该添加数量
这是我的 cartItems:
let cartItems = [
{ id: 1, price: 120, quantity: 7 },
{ id: 2, price: 70, quantity: 4 },
{ id: 1, price: 70, quantity: 3 },
{ id: 3, price: 60, quantity: 1 },
{id: 1, price: 120, quantity: 2}
];
这是我的foodItems
let foodItems = [
{
id: 1,
name: "chicken",
itemDetails: [
{
price: 120,
details: "2 pcs of chicken biryani"
},
{
price: 70,
details: "1 pcs of chicken biryani"
}
],
},
{
id: 2,
name: "Mutton",
itemDetails: [
{
price: 120,
details: "Two pieces of mutton biryani",
},
{
price: 70,
details: "one pcs of mutton biryani"
},
],
},
{ id: 3, name: "Ice Cream", price: 60 },
];
这是我想要的输出
let filteredArrayOuput = [
{
id: 1,
name: "Chicken Biryani",
itemDetails: [
{
price: 120,
details: "Two pieces of chicken Biryani",
},
],
quantity: 7,
},
{
id: 2,
name: "Mutton Biryani",
itemDetails: [
{
price: 70,
details: "Two pieces of mutton biryani",
},
],
quantity: 4,
},
{
id: 1,
price: "Chicken Biryani",
quantity: 3,
itemDetails: [
{
price: 70,
details: "Two pieces of Chicken Biryani",
},
],
},
{ id: 3, price: 60, quantity: 1 },
];
这就是我到目前为止所做的事情
const filterFunc = (arr, price) => {
let filtered = arr.filter((item) => {
return item.price == price;
});
return filtered;
};
const filterArray = (arr1, arr2) => {
const filtered = arr2.filter((el) => {
let arr = arr1.find(({ id, quantity, price }) => {
if (el.id === id) {
if (el.itemDetails !== undefined && el.itemDetails.length !== 0) {
let itemDetails = el.itemDetails;
return (
(el.quantity = quantity),
(el.itemDetails = filterFunc(itemDetails, price))
);
} else {
return (el.quantity = quantity);
}
}
});
return arr;
});
return filtered;
};
console.log(filterArray(cartItems, foodItems))
【问题讨论】:
-
if (el.id === id) { console.log(id, price); return id;如果您返回 id,那么您将永远不会进入下一个代码块。 -
对不起,我已经删除了return语句。
标签: javascript arrays object filter