嘿伙計們,我希望有人可以幫助我。我有物件陣列
const users = [
{
id: "2222",
name: "Peter",
age: 20,
carts: [
{
productId: "1a3va",
price: 3.44,
quantity: 3,
},
{
productId: "3adf4",
price: 8.44,
quantity: 5,
},
],
},
{
id: "43443",
name: "John",
age: 24,
carts: [
{
productId: "2334a",
price: 13.44,
quantity: 13,
},
{
productId: "4234d",
price: 1.44,
quantity: 1,
},
],
},
];
然后我的任務是函式invoiceCustomer-> 回傳購物車中物品的總價值,對于給定的客戶,帶有建議的引數。并且因為totalOrderValue它應該回傳訂單的總價值。
function invoiceCustomer(users, id, name, age) {}
function totalOrderValue(order) {}
我已經嘗試過 map 和 reduce 但即使我使用 parseInt 也會出現 NaN 錯誤。
我希望有人能幫我解決這個問題。謝謝!
uj5u.com熱心網友回復:
我認為這應該有效。
function totalOrderValue(users, id, name, age) {
let user = users.filter( (item, index, array) => {
// Used only one criteria (id) for example simplicity
return item.id === id;
});
if (user.length === 1) {
return user[0].carts.reduce((prevValue, item) => {
return prevValue (item.price * item.quantity);
}, 0); // Important: initialize prevValue to 0
} else if (user.length === 0) {
throw 'User not found';
} else {
throw 'Too many users found';
}
}
我無法幫助您使用該totalOrderValue函式,因為沒有用于過濾資料的 orderId,但是您明白了使用filter和reduce方法的要點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328709.html
標籤:javascript 数组 目的
