[英]How to check an array of objects against another one?
你好,
我有一組對象,其中包含所有項目及其各自的價格,如下所示:
var items = [
{
"id": "001",
"name": "apple",
"price": 500
},
{
"id": "002",
"name": "banana",
"price": 700
},
{
"id": "003",
"name": "pear",
"price": 200
}
];
然后我有一個客戶的車是這樣的:
var cart = [{
"id": "001",
"qty": 2
},
{
"id": "002",
"qty": 3
},
{
"id": "003",
"qty": 4
}
];
客戶的信用存儲在一個變量中。 我想檢查第二個數組與第一個數組以獲得購物車的總數,並確保它不會超過客戶的信用額度。 我不知道該怎么做。 我試過了:
var mytotal=cart.map(d => {
var total=0;
items.forEach(rm => {
total = total+(d.qty*rm.price);
} return total;
});
if(credit >= total) {//dosomething}
但它沒有用。 什么是正確的方法?
謝謝你。
您可以將問題分為兩個任務:連接和求和。
const joined = items.map(item => ({...item, ...cart.find(c => c.id === item.id)}));
請注意,如果 id 不匹配, find
將返回null
,並且展開 ( ...
) 不會導致 object 發生變化
const sum = joined.reduce((sum, curr) => sum += curr.price * curr.qty, 0);
一個更安全的版本是:
const sum = joined.reduce((sum, curr) => sum += (curr.price ?? 0) * (curr.qty ?? 0), 0);
var items = [ { "id": "001", "name": "apple", "price": 500 }, { "id": "002", "name": "banana", "price": 700 }, { "id": "003", "name": "pear", "price": 200 } ]; var cart = [{ "id": "001", "qty": 2 }, { "id": "002", "qty": 3 }, { "id": "003", "qty": 4 } ]; const joined = items.map(item => ({...item, ...cart.find(c => c.id === item.id)})); const sum = joined.reduce((sum, curr) => sum += curr.price * curr.qty, 0); console.log(`joined object is: `, joined); console.log(`sum is: ${sum}`);
要實現可重用且高效的解決方案,您可以在items
數組上創建一個查找表,此處使用Map
,它允許您通過id
直接訪問該項目。
const itemLookup = new Map(items.map((item) => [item.id, item]))
// Map(3) {
// '001' => { id: '001', name: 'apple', price: 500 },
// '002' => { id: '002', name: 'banana', price: 700 },
// '003' => { id: '003', name: 'pear', price: 200 }
// }
然后,您可以創建一個getCartTotal
幫助程序,它將使用查找表計算傳遞給它的購物車總數。 (這里我們假設任何將在購物車中的項目也將在項目數組中,但為了安全起見,您可以添加可選鏈接, t += (itemLookup.get(id)?.price?? 0) * qty
)
const getCartTotal = (cart) => {
return cart.reduce((t, { id, qty }) => (
t += itemLookup.get(id).price * qty
), 0);
}
結果使您可以在購物車發生變化時有效地對其重新求和。
const items = [{ "id": "001", "name": "apple", "price": 500 }, { "id": "002", "name": "banana", "price": 700 }, { "id": "003", "name": "pear", "price": 200 }]; const itemLookup = new Map(items.map(({ id, ...item }) => [id, { id, ...item }])); const getCartTotal = (cart) => { return cart.reduce((total, { id, qty }) => ( total += itemLookup.get(id).price * qty ), 0); } const cart = [{ "id": "001", "qty": 2 }, { "id": "002", "qty": 3 }, { "id": "003", "qty": 4 }]; console.log(getCartTotal(cart)); // 3900 cart[0].qty += 2; console.log(getCartTotal(cart)); // 4900
我在比賽中有點晚了,但也許下面的片段仍然很有趣? 它采用了創建查找 object itms
的想法,並且對於每個購物車條目,它還將兩個對象組合成一個帶有小計subt
的新對象,因此您可以輕松創建一個有意義的購物車表。 變量ttl
一起更新並包含總和:
const items = [ { "id": "001", "name": "apple", "price": 500 }, { "id": "002", "name": "banana", "price": 700 }, { "id": "003", "name": "pear", "price": 200 } ], cart = [{ "id": "001", "qty": 2 }, { "id": "002", "qty": 3 }, { "id": "003", "qty": 4 } ]; // Turn the items array into an object, facilitating a fast lookup: const itms=items.reduce((a,c)=>(a[c.id]=c,a),{}); let ttl=0; // calculate the totals: const res=cart.map(c=>{ const p=itms[c.id], subt=c.qty*p.price; ttl+=subt; return {...c,...p,subt} }) // Show the result: console.log(res,ttl);
在您的嘗試中,您將 map function 應用於購物車數組。 Map 將 function 應用於數組的每個元素,並返回新數組。 function total = 0 等分別應用於每個元素。
在 map/reduce 工作方式中,嘗試先使用 map 獲取每個購物車元素的正確價格,然后使用 reduce 進行匯總。 Map/reduce 只是解決此問題的眾多方法之一,您也可以像在 map function 中嘗試的那樣使用 for 循環迭代地執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.