问题描述
对数组中的对象进行分组的最有效方法是什么?
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.
我正在使用Underscore.js作为其groupby函数,这很有帮助,但是没有不要做整个技巧,因为我不希望它们拆分但是合并,更像是组的SQL 组。
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.
我正在寻找的是能够总计特定值(如果要求)。
What I’m looking for would be able to total specific values (if requested).
所以如果我做了groupby 阶段
,我想收到:
So if I did groupby Phase
, I’d want to receive:
[
{ Phase: "Phase 1", Value: 50 },
{ Phase: "Phase 2", Value: 130 }
]
如果我做了分组阶段
/ Step
,我会收到:
And if I did groupy Phase
/ Step
, I’d receive:
[
{ 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 }
]
是否有一个有用的脚本,或者我应该坚持使用Underscore.js,然后循环结果对象自己做总计?
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?
推荐答案
如果你想避免使用外部库,你可以简洁地实现一个vanilla版本的 groupBy()
,如下所示:
If you want to avoid external libraries, you can concisely implement a vanilla version of groupBy()
like so:
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
console.log(groupBy(['one', 'two', 'three'], 'length'));
// => {3: ["one", "two"], 5: ["three"]}
这篇关于分组对象数组的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!