I have an array of objects. The simplified version (with just a few of the properties):
let d = [
{ team:"sales", key:"employees", value:24 },
{ team:"sales", key:"floor", value:2 },
{ team:"finance", key:"employees", value:7 },
{ team:"finance", key:"floor", value:2 },
]
Want to group by team and then by key, using plain (ES6) JavaScript:
{
sales: {
employees: { team:"sales", key:"employees", value:24 },
floor: { team:"sales", key:"floor", value:2 }
},
finance: {
employees: { team:"finance", key:"employees", value:7 },
floor: { team:"finance", key:"floor", value:2 }
}
}
Somewhat similar to other questions, but not quite.
What I have so far: using reduce to group by team:
let groupBy = (data, field) => data.reduce((acc, obj) => Object.assign(acc, { [obj[field]]:( acc[obj[field]] || [] ).concat(obj) }), {})
let result = groupBy(d,'team')
This gives:
{
sales: [
{ team:"sales", key:"employees", value:24 },
{ team:"sales", key:"floor", value:2 }
],
finance: [
{ team:"finance", key:"employees", value:7 },
{ team:"finance", key:"floor", value:2 }
]
}
Not sure what the recommended way is to group by the key level inside the teams.