javascript - 在找到匹配索引的javascript中加入两个数组
问题描述
我有两个通过 AJAX 传递的单独数组。第一个称为 cartArray,包含与添加到购物车的产品相关的数据,console.log 显示它包含此数据。
max_allowed: 10
product_id: 4202
product_name: "34 inch Gold Number 1 Foil Balloon (1)"
qty: 3
第二个称为 cartqtyArray,是在添加到购物车操作发生之前当前购物车数量的计数。console.log 显示它包含这个。
0: {product_id: 4202, basket_qty: 2}
1: {product_id: 4203, basket_qty: 10}
2: {product_id: 0, basket_qty: 0}
3: {product_id: 0, basket_qty: 0}
4: {product_id: 0, basket_qty: 0}
5: {product_id: 0, basket_qty: 0}
6: {product_id: 0, basket_qty: 0}
7: {product_id: 0, basket_qty: 0}
8: {product_id: 0, basket_qty: 0}
9: {product_id: 0, basket_qty: 0}
10: {product_id: 0, basket_qty: 0}
我需要做的是组合这两个数组,如果它存在于 cartArray 中,则匹配 product_id。任何没有匹配 product_id 的地方都可以丢弃。
所以最终我会得到一个新的数组,比如
max_allowed: 10
product_id: 4202
product_name: "34 inch Gold Number 1 Foil Balloon (1)"
qty: 3
basket_qty: 2
我看着使用地图,但所有的例子似乎都在使用数组结构,如
a = [1, 2, 3, 4],
b = [34, 54, 54, 43],
这不代表我拥有的数组类型。
一些关于什么功能可以用来做我需要的事情的指针将不胜感激。
解决方案
您可以使用reduce、find和对象解构来获得所需的结果。
const cartArray = [{
max_allowed: 10,
product_id: 4202,
product_name: "34 inch Gold Number 1 Foil Balloon (1)",
qty: 3,
}, {
max_allowed: 10,
product_id: 7,
product_name: "34 inch Gold Number 1 Foil Balloon (1)",
qty: 3,
}];
const cartqtyArray = [{
product_id: 4202,
basket_qty: 2
},
{
product_id: 4203,
basket_qty: 10
},
{
product_id: 0,
basket_qty: 0
},
{
product_id: 0,
basket_qty: 0
},
{
product_id: 0,
basket_qty: 0
},
{
product_id: 0,
basket_qty: 0
},
{
product_id: 0,
basket_qty: 0
},
{
product_id: 0,
basket_qty: 0
},
{
product_id: 0,
basket_qty: 0
},
{
product_id: 0,
basket_qty: 0
},
{
product_id: 0,
basket_qty: 0
},
];
const result = cartArray.reduce((acc, cart) => {
const cartItemInCartQty = cartqtyArray.find(
(x) => x.product_id === cart.product_id
);
if (cartItemInCartQty) {
acc.push({ ...cart,
...cartItemInCartQty
});
} else {
acc.push(cart)
}
return acc;
}, []);
console.log(result);
推荐阅读
- c# - 如何从代码优先实体框架中的不可空列中删除默认值
- ios - 在 IOS 中使用 AUGraph 在 AudioUnit 中播放立体声
- python - 从现有值中添加值,Python 字典
- javascript - vue-ctk-date-time-picker 2 如何将下拉位置更改为正确?
- cron - 启用 SELinux 的 NFS 共享 Oracle Linux 8 集群上的 Cron 作业失败
- javascript - 如何在 React 中同时构建受控和不受控的 Input 组件?
- nuxt.js - 用于特定路由的 NuxtJS 路由中间件
- r - R - 滚动窗口上的产品总和(四分之一)
- flutter - 导航计入颤动
- windows - Windows 上的电子吐司操作