gpt4 book ai didi

javascript - 如何计算 json 对象中的属性不同值

转载 作者:行者123 更新时间:2023-11-30 09:35:06 24 4
gpt4 key购买 nike

我正在从数据库中获取一个 json 对象。计算 ClassDefA、B、C 数量的最佳做法是什么。
在 json 对象中,例如:我在这个 json 中有“2 A 和 2 B 和 3 c”

我的 json 对象:

[{
"ItemCode": "200500303800356",
"LastCost": 8,
"OnHand": 593889,
"InventoryValue": 4751112,
"PercOfTotalInventory": 18.294517,
"CumerativePercTotal": 18.29,
"ClassDef": "A"
}, {
"ItemCode": "201600701800197",
"LastCost": 400,
"OnHand": 300,
"InventoryValue": 120000,
"PercOfTotalInventory": 0.462069,
"CumerativePercTotal": 75.68,
"ClassDef": "A"
}, {
"ItemCode": "200701507000107",
"LastCost": 75,
"OnHand": 239,
"InventoryValue": 17925,
"PercOfTotalInventory": 0.069022,
"CumerativePercTotal": 91.75,
"ClassDef": "B"
}, {
"ItemCode": "200501303400308",
"LastCost": 3515,
"OnHand": 5,
"InventoryValue": 17575,
"PercOfTotalInventory": 0.067674,
"CumerativePercTotal": 91.81,
"ClassDef": "B"
}, {
"ItemCode": "200200106701035",
"LastCost": 80,
"OnHand": 27,
"InventoryValue": 2160,
"PercOfTotalInventory": 0.008317,
"CumerativePercTotal": 99.28,
"ClassDef": "C"
}, {
"ItemCode": "200200902700248",
"LastCost": 10,
"OnHand": 213,
"InventoryValue": 2130,
"PercOfTotalInventory": 0.008202,
"CumerativePercTotal": 99.29,
"ClassDef": "C"
}, {
"ItemCode": "200601302001093",
"LastCost": 0.3,
"OnHand": 6,
"InventoryValue": 1.8,
"PercOfTotalInventory": 0.000007,
"CumerativePercTotal": 100,
"ClassDef": "C"
}]

有人知道怎么做吗?

最佳答案

您可以使用对象作为结果并使用 ClassDef 作为键。

var data = [{ ItemCode: "200500303800356", LastCost: 8, OnHand: 593889, InventoryValue: 4751112, PercOfTotalInventory: 18.294517, CumerativePercTotal: 18.29, ClassDef: "A" }, { ItemCode: "201600701800197", LastCost: 400, OnHand: 300, InventoryValue: 120000, PercOfTotalInventory: 0.462069, CumerativePercTotal: 75.68, ClassDef: "A" }, { ItemCode: "200701507000107", LastCost: 75, OnHand: 239, InventoryValue: 17925, PercOfTotalInventory: 0.069022, CumerativePercTotal: 91.75, ClassDef: "B" }, { ItemCode: "200501303400308", LastCost: 3515, OnHand: 5, InventoryValue: 17575, PercOfTotalInventory: 0.067674, CumerativePercTotal: 91.81, ClassDef: "B" }, { ItemCode: "200200106701035", LastCost: 80, OnHand: 27, InventoryValue: 2160, PercOfTotalInventory: 0.008317, CumerativePercTotal: 99.28, ClassDef: "C" }, { ItemCode: "200200902700248", LastCost: 10, OnHand: 213, InventoryValue: 2130, PercOfTotalInventory: 0.008202, CumerativePercTotal: 99.29, ClassDef: "C" }, { ItemCode: "200601302001093", LastCost: 0.3, OnHand: 6, InventoryValue: 1.8, PercOfTotalInventory: 0.000007, CumerativePercTotal: 100, ClassDef: "C" }],
result = data.reduce(function (r, o) {
r[o.ClassDef] = (r[o.ClassDef] || 0) + 1;
return r;
}, Object.create(null));

console.log(result);

关于javascript - 如何计算 json 对象中的属性不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44042548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com