【发布时间】:2021-11-26 20:49:10
【问题描述】:
我有一个目前看起来像这样的数据集:
let cart_items = [
{
"id": "817fd815-302c-401a-b087-6781f073a2bf",
"date": "2021-09-10",
"notes": "null",
"quantity": 2,
"is_special": true,
"mobile_price": "1.21",
"item_name": "Cranberry",
"menu_name": "Breakfast",
"item_photo": "loading",
"cart_add_ons": [
]
},
{
"id": "817fd815-302c-401a-b087-6781f073a2bf",
"date": "2021-09-11",
"notes": "null",
"quantity": 2,
"is_special": true,
"mobile_price": "7.21",
"item_name": "Cranberry",
"menu_name": "Breakfast",
"item_photo": "loading",
"cart_add_ons": [
{
"name": "Cake",
"mobile_price": "2.3"
},
{
"name": "Milk",
"mobile_price": "12"
}
]
},
{
"id": "817fd815-302c-401a-b087-6781f073a2bf",
"date": "2021-09-10",
"notes": "null",
"quantity": 2,
"is_special": true,
"mobile_price": "5.21",
"item_name": "Raspberry",
"menu_name": "Breakfast",
"item_photo": "loading",
"cart_add_ons": [
{
"name": "Cake",
"mobile_price": "2.3"
},
{
"name": "Milk",
"mobile_price": "12"
}
]
}
];
如果 cart_add_ons 有任何数据,我实际上是在尝试将 cart_add_ons 中的所有附加价格相加。
我正在尝试使用以下方式来实现这一点,但我知道这是不正确的。是否接近正确的解决方案?
result = _.chain(cart_items)
.groupBy('date')
.map((value, key) => ({
date: key,
total_amount: _.sumBy(value, item => Number(item.mobile_price)),
total_add_on: _.sumBy(value, function(o) { return o.cart_add_ons ? Number(o.cart_add_ons.mobile_price) : 0; }),
item_data: value,
}))
.sortBy('date')
.value();
顺便说一句,这是上述问题的结果:
[
{
"date": "2021-09-10",
"total_amount": 6.42,
"total_add_on": null,
"item_data": [
{
"id": "817fd815-302c-401a-b087-6781f073a2bf",
"date": "2021-09-10",
"notes": "null",
"quantity": 2,
"is_special": true,
"mobile_price": "1.21",
"item_name": "Cranberry",
"menu_name": "Breakfast",
"item_photo": "loading",
"cart_add_ons": []
},
{
"id": "817fd815-302c-401a-b087-6781f073a2bf",
"date": "2021-09-10",
"notes": "null",
"quantity": 2,
"is_special": true,
"mobile_price": "5.21",
"item_name": "Raspberry",
"menu_name": "Breakfast",
"item_photo": "loading",
"cart_add_ons": [
{
"name": "Cake",
"mobile_price": "2.3"
},
{
"name": "Milk",
"mobile_price": "12"
}
]
}
]
},
{
"date": "2021-09-11",
"total_amount": 7.21,
"total_add_on": null,
"item_data": [
{
"id": "817fd815-302c-401a-b087-6781f073a2bf",
"date": "2021-09-11",
"notes": "null",
"quantity": 2,
"is_special": true,
"mobile_price": "7.21",
"item_name": "Cranberry",
"menu_name": "Breakfast",
"item_photo": "loading",
"cart_add_ons": [
{
"name": "Cake",
"mobile_price": "2.3"
},
{
"name": "Milk",
"mobile_price": "12"
}
]
}
]
}
]
请让我知道我哪里出了问题。
【问题讨论】:
标签: javascript node.js arrays object lodash