Before we proceed, let's clarify whether b is an array or an object in your code. Are you using it as both? It seems like you intended for it to be an anonymous object.
let b = {};
It would also be beneficial to understand the precise structure of user.jobworker (you can use "JSON.stringify(user.jobworker)" to check). For now, let's assume that the user object has the following structure:
{
name: "Mike Smith",
id: 281,
duration: 5,
jobworker: [284, 281]
}
If this is accurate, you can achieve what you need by doing the following:
let b = {};
this.state.sidejobs.forEach((user) => {
for (var i = 0; i < user.jobworker.length; i++) {
if (!b.hasOwnProperty(user.jobworker[i])) b[user.jobworker[i]] = 0;
b[user.jobworker[i]] += user.duration;
}
});
If user.jobworker actually consists of a comma-delimited string of ids (e.g., user.jobworker = "284,281"), then you'll need to split the string first:
this.state.sidejobs.forEach((user) => {
var jobworkers = user.jobworker.split(",");
for (var i = 0; i < jobworkers.length; i++) {
var worker = jobworkers[i].trim();
if (!b.hasOwnProperty(worker)) b[worker] = 0;
b[worker] += user.duration;
}
});