如何生成每一个订单的总价格?

现在我有一组数组对象,WXK2X0`AOFWU}QC3K%~0LKH.png

这组数组对象的内部含有如图所示所示的products的对象数据Snipaste_2021-11-02_14-48-36.png

products内部有如图所示的属性,Snipaste_2021-11-02_14-50-44.png

现在我想要计算每层对象下的 proucts总价格,
但我只会通过for in遍寻计算出全部的总价格。求大佬赐教!也就是一个订单一个总价Snipaste_2021-11-02_14-53-53.png一下

阅读 1.6k
1 个回答
const orderPrices = Object.fromEntries(
    orders.map((order) => [
        order.order_no,
        order.products.reduce((prev, cur) => prev + +cur.price, 0),
    ])
);

或者你要数组形式的

const orderPrices = orders.map((order) => ({
    order_no: order.order_no,
    totalPrice: order.products.reduce((prev, cur) => prev + +cur.price, 0),
}));
推荐问题