I have a temp array which originally looks something like this :
[{emp_id:1, acitivty:'run'}, {emp_id: 2, activity:'climb'}, {emp_id:1,activity:'swim'} .....]
Now, what I want is to merge the objects with the same emp_id. It should look like this:
[{emp_id:1, activity:'run', activity2:'swim'}, {emp_id:'2',activity:'climb'} .....]
Instead, I only got this, not showing the rest of the objects in the array:
[{emp_id:'1', activity:'run', activity2:'swim'}]
In my code, when the condition is met and the merging and splicing is done, I decrement the z because I think after splicing, the array will be reindexed and I think the array length will still be as is.
What seems to be the problem?
for(var z = 0; z < temp.length; z++) {
for(var x = 1; x < temp.length; x++) {
if(temp[z].emp_id == temp[x].emp_id) {
var ot_key = 'ot_time'+x+1;
var status_key = 'status'+x+1;
var dtr_key = 'dtr_out'+x+1;
Object.assign(temp[z], {
[ot_key] : temp[x].ot_time,
[status_key] : temp[x].status,
[dtr_key] : temp[x].dtr_out
})
temp.splice(x, 1);
z--;
}
}
}