What is the most efficient way to groupby objects in an array?
(在数组中对对象进行分组的最有效方法是什么?)
For example, given this array of objects:
(例如,给定此对象数组:)
[
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
]
I'm displaying this information in a table.
(我正在表中显示此信息。)
I'd like to groupby different methods, but I want to sum the values.(我想对不同的方法进行分组,但是我想对这些值求和。)
I'm using Underscore.js for its groupby function, which is helpful, but doesn't do the whole trick, because I don't want them “split up” but “merged”, more like the SQL group by
method.
(我将Underscore.js用于其groupby函数,这很有用,但并不能解决所有问题,因为我不希望它们“分裂”而是“合并”,更像SQL group by
方法。)
What I'm looking for would be able to total specific values (if requested).
(我正在寻找的是能够总计特定值(如果需要)。)
So if I did groupby Phase
, I'd want to receive:
(因此,如果我按Phase
进行groupby,则希望收到:)
[
{ Phase: "Phase 1", Value: 50 },
{ Phase: "Phase 2", Value: 130 }
]
And if I did groupy Phase
/ Step
, I'd receive:
(如果我对Phase
/ Step
进行了分组,则会收到:)
[
{ Phase: "Phase 1", Step: "Step 1", Value: 15 },
{ Phase: "Phase 1", Step: "Step 2", Value: 35 },
{ Phase: "Phase 2", Step: "Step 1", Value: 55 },
{ Phase: "Phase 2", Step: "Step 2", Value: 75 }
]
Is there a helpful script for this, or should I stick to using Underscore.js, and then looping through the resulting object to do the totals myself?
(是否为此提供有用的脚本,还是应该坚持使用Underscore.js,然后循环遍历生成的对象来自己进行总计?)
ask by Rail24 translate from so