![](/img/trans.png)
[英]how to map properties of two object arrays with different lengths in JavaScript
[英]How to map two arrays with different lengths? (Javascript)
因此,我有兩個包含價格的數組。 一個是底價,其他是添加劑
const fees = [{ price: 5, title: "normal tarif" }, { price: 2.5, title: "coupon" }]; const extras = [{ price: 2.00, title: "Extra natchos" }, { price: 2.00, title: "Extra sauce" }, { price: 3.00, title: "Extra spicy" }]; const combinedArray = fees.map((x, i) => [x.price, x.price + extras[i].price]); console.log(combinedArray);
現在,我需要將它們重新映射到一個新的數組中,這會將它們的價格加在一起,但是,我目前擁有的代碼僅能達到第一個數組中元素的數量。
我如何才能使它也能映射第二個數組中的所有元素?
您可以將給定數組的所有價格相加,然后返回一個包含每個數組總和的新數組。
var fees = [{ price: 5, title: "normal tarif" }, { price: 2.5, title: "coupon" }], extras = [{ price: 2.00, title: "Extra natchos" }, { price: 2.00, title: "Extra sauce" }, { price: 3.00, title: "Extra spicy" }], prices = [fees, extras] .map(a => a .map(({ price }) => price) .reduce((a, b) => a + b, 0)); console.log(prices);
要將兩個陣列合並為一個,需要執行更多操作。 這是示例代碼:
const fees = [{ price: 5, title: "normal tarif" }, { price: 2.5, title: "coupon" }]; const extras = [{ price: 2.00, title: "Extra natchos" }, { price: 2.00, title: "Extra sauce" }, { price: 3.00, title: "Extra spicy" }]; const combinedArray = [].concat(...fees.map(fee => extras.map(extra => fee.price + extra.price))); console.log(combinedArray);
內部部分通過將每個fee
映射到fee
和extra
數組來創建二維數組, [].concat(...array2D)
部分將其轉換為一維數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.