我试图将以下数组与对象分组:
[ { user_id: 301, alert_id: 199, deal_id: 32243 },
{ user_id: 301, alert_id: 200, deal_id: 32243 },
{ user_id: 301, alert_id: 200, deal_id: 107293 },
{ user_id: 301, alert_id: 200, deal_id: 277470 } ]
如您所见,它包含user_id和alert_id组合,我喜欢将其分组。所以我想拥有以下数组:
[ { user_id: 301, alert_id: 199, deals: [32243] },
{ user_id: 301, alert_id: 200, deals: [32243,107293,277470]}]
任何人都知道解决方案吗?使用下划线的GroupBy,我可以根据一个键对值进行分组。但是我需要根据你看到的组合user_id AND alert_id对它们进行分组。
我看了underscore.nest,但问题是它创建了自己的密钥。
答案 0 :(得分:82)
将groupBy与使用user_id和alert_id创建复合键的函数一起使用。然后映射分组以获得您想要的内容:
var list = [ { user_id: 301, alert_id: 199, deal_id: 32243 },
{ user_id: 301, alert_id: 200, deal_id: 32243 },
{ user_id: 301, alert_id: 200, deal_id: 107293 },
{ user_id: 301, alert_id: 200, deal_id: 277470 } ];
var groups = _.groupBy(list, function(value){
return value.user_id + '#' + value.alert_id;
});
var data = _.map(groups, function(group){
return {
user_id: group[0].user_id,
alert_id: group[0].alert_id,
deals: _.pluck(group, 'deal_id')
}
});
答案 1 :(得分:0)
我想贡献一个整洁的打字稿ES6小组。
我不太确定如何加强返回值的输入。那里需要一些技巧,但这对我来说很好。
/**
* group the supplied list by a set of keys.
* @param list the list of items to group.
* @param children the key for the array of child items.
* @param components the components to group by.
*/
groupByMultipleFields<T, K extends keyof T>(
list: T[],
children: string,
...components: K[]): any[] {
var grouping = [...list.reduce((r, o) => {
const key = components.map(_ => `${o[_]}`).join(" :: ");
var keyed = r.get(key) || components.reduce((x, y) => { x[y] = o[y]; return x; }, <T>{});
keyed[children] = keyed[children] || [];
keyed[children].push(o);
return r.set(key, keyed);
}, new Map).values()];
return grouping;
}
您将需要打开打字稿编译器选项"downlevelIteration": true
,以允许new Map
进行迭代并返回values()
。
答案 2 :(得分:0)
对于某些特定任务,我必须为其保护键和值 所以我做了这个变体(使用干净的js):
/**
* Group your items in array by multiple keys!
*
* @param collection
* @param retrieveFunctions
* @param compareFunctions
* @returns {Array}
*/
function groupify(
collection,
retrieveFunctions = {attribute: value => value},
compareFunctions = {attribute: (groupValue, value) => groupValue === value}
) {
let groups = [];
let keyValues = {};
collection.forEach(item => {
for (let attribute in retrieveFunctions) {
keyValues[attribute] = retrieveFunctions.hasOwnProperty(attribute) ? retrieveFunctions[attribute](item[attribute]) : undefined;
}
let group = groups.find(group => {
for (let key in retrieveFunctions) {
if (!group && !group.keys[key]) {
return false;
}
if (compareFunctions[key] instanceof Function) {
if (!compareFunctions[key](group.keys[key], keyValues[key])) {
return false;
}
} else if (group.keys[key] !== keyValues[key]) {
return false;
}
}
return true;
});
!group ? groups.push({keys: keyValues, items: [item]}) : group.items.push(item);
keyValues = {};
});
return groups;
}
这里是要点上的链接: groupify.js