I have a pretty simple setup like this:
var itemsPerAssignee = {}
My plan is to save the amount of items in this object, so I can later iterate over it and, depending on the key, output the specific value on how many items are left for that specific user.
In my for-loop I iterate like this, to fill the object:
query.forEach(function (task) {
var assignee = task.getAssignee();
itemsPerAssignee[assignee] = {count: 0}
}
this at least doesn’t yield an error, but my output doesn’t seem to update. So I basically would need to check, if there is a value already existing for that specific key. If so, I need to increment it by 1.
I know I could have a function to check that specific index of the object, read the value, adjust and write it. But that doesn’t seem clean. I’m pretty sure there is an easier way to do so, but I don’t know how.
I also fiddled around with something like:
itemsPerAssignee = {user: assignee, count: 0}
but I got stuck there and I don’t know if my approach was correct.
Also, right now, I have objects with the same key multiple times, which might be part of the problem. Can someone point me in the right direction?
var itemsPerAssignee = {};
var users = ["[email protected], [email protected]", "[email protected]"];
for(u in users) {
itemsPerAssignee[u] = {count: 0};
}
for(i in itemsPerAssignee) {
console.log(itemsPerAssignee[i].count);
}
5
Answers
Just check if exists, then create or update
If assignee is an actual value (like an id or email, a unique key) and not an object…
Since you want to count the number of items for each assignee in your task list and store it in the object, but here you are not incrementing the count, the correct code to increment items will be:
You can use the Nullish coalescing assignment:
Just for fun and giggles, here’s an one-liner solution using
Object.groupBy
which has the worst compatibility that no one should use:Can be done with one line: