首页 > 解决方案 > 在找到匹配索引的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],

这不代表我拥有的数组类型。

一些关于什么功能可以用来做我需要的事情的指针将不胜感激。

标签: javascriptarrays

解决方案


您可以使用reducefind对象解构来获得所需的结果。

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);


推荐阅读