簡體   English   中英

在找到匹配索引的 javascript 中加入兩個 arrays

[英]Join two arrays in javascript where a matching index is found

我有兩個單獨的 arrays 通過 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}

我需要做的是結合兩個 arrays,如果它存在於 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

我查看了使用 map,但所有示例似乎都使用了類似的數組結構

a = [1, 2, 3, 4],
b = [34, 54, 54, 43],

這不代表我擁有的 arrays 類型。

一些關於 function 可用於做我需要的事情的指針將不勝感激。

您可以使用reducefindobject 解構來獲得所需的結果。

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

如果您有大型列表要合並,那么考慮時間復雜度也會很好。 也許你可以試試下面的片段

 const cartqtyArrayHash = cartqtyArray.reduce((acc, prod)=> { acc[prod.product_id] =prod; return acc; }, {}); const result = cartArray.map(cart => Object.assign({}, cart, cartqtyArrayHash[cart.product_id]));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM