提问人:Chris 提问时间:8/19/2022 更新时间:8/19/2022 访问量:237
计算嵌套对象中某些键的值总和
Calculate the sum of values from certain keys in nested objects
问:
我有一个购物车对象,例如:
const shopCart = {
"4509563079435": {
name: "product 1",
price: 29.99,
quantity: 2,
subtotal: 59.98,
},
"5678327300382": {
name: "product 2",
price: 90.49,
quantity: 1,
subtotal: 90.49,
},
"8612061865613": {
name: "product 3",
price: 58.99,
quantity: 2,
subtotal: 117.98,
},
};
项目 ID 可以是任何内容,也可以是任意数量的项目。
我想将所有小计相加以得出此购物车的总数,并将其保存在变量中。
我知道如何使用平面对象(reduce 或 sum)执行此操作,但是我在迭代嵌套项时遇到了麻烦。
提前致谢:)
答:
0赞
Chris
8/19/2022
#1
我在这里发帖后一分钟就自己想通了:)
const shopCart = {
"4509563079435": {
name: "product 1",
price: 29.99,
quantity: 2,
subtotal: 59.98,
},
"5678327300382": {
name: "product 2",
price: 90.49,
quantity: 1,
subtotal: 90.49,
},
"8612061865613": {
name: "product 3",
price: 58.99,
quantity: 2,
subtotal: 117.98,
},
};
const total = Object.values(shopCart).reduce((acc, curr) => (acc = acc + curr["subtotal"]), 0);
console.log(total);
我需要使用 Object.values,它返回所有项目的数组。 然后,reduce 方法可以对指示键中的值求和。
希望这能帮助像我这样被困了一段时间的人:)
上一个:如何键入嵌套对象?
评论