You should be assigning each object not found to the result with its .key
property.
If it is found, then you need to add its .val
.
var temp = {};
var obj = null;
for(var i=0; i < objArr.length; i++) {
obj=objArr[i];
if(!temp[obj.key]) {
temp[obj.key] = obj;
} else {
temp[obj.key].val += obj.val;
}
}
var result = [];
for (var prop in temp)
result.push(temp[prop]);
Also, part of the problem was that you were reusing the item
variable to reference the value of .key
, so you lost reference to the object.