Reputation: 2877
For my time-tracking app, I'm storing time entries in an array of objects each looking like this:
{
date: "20181206",
hours: "4",
projectId: "65WchP9X46HlOYUzmWrL",
taskId: "fJTU7wggJHbg1uRuRUdHjS5mn8J3"
}
I need to group, into separate arrays, all objects by unique combinations of ProjectId
- TaskId
properties, so that each resulting array gets all entries for one particular project and one particular task (an array for project #1
/ task #1
, another for project #1
/ task #2
, another for project #2
/ task #1
, etc).
I know how to do that with one property, but is there a simple way to achieve the same with two properties?
Note: my global array is initially populated like so:
weekTimes = [];
querySnapshot.forEach((doc) => {
weekTimes.push(doc.data());
});
Upvotes: 0
Views: 171
Reputation: 214927
Create a composite key from projectId
and taskId
:
grouped = {}
for (weekTime of weekTimes) {
var key = `${weekTime.projectId}/${weekTime.taskId}`
if (grouped[key] === undefined) {
// if the key doesn't exist, weekTime is the first item, create the key
// and assign an array with the first item to it
grouped[key] = [ weekTime ]
} else {
// if the key already exists in grouped, just push new item to that key
grouped[key].push(weekTime)
}
}
// if you don't need the keys
Object.values(grouped)
Or use lodash
groupby
:
const _ = require('lodash')
_.groupBy(weekTimes, x => x.projectId + '/' + x.taskId)
Upvotes: 1