Merge objects with same key in javascript

Viewed 1769

I have been trying to figure this out for a long time, if i have an array of objects like so:

var my_array = [
    Object {Project: A, Hours: 2},
    Object {Project: B, Hours: 3},
    Object {Project: C, Hours: 5},
    Object {Project: A, Hours: 6},
    Object {Project: C, Hours: 9}
]

I want to merge all the objects with the same key together into one object, such that their hours get added up:

Expected output:

my_array = [
    Object {Project: A, Hours: 8}
    Object {Project: B, Hours: 3}
    Object {Project: C, Hours: 14}
]

How can I approach this issue? It has taken me a long time to get my data formatted in this way, this is the last step!

My attempt, I get that I am looping through array, not sure how to deal with the merging of the objects:

for (var i =0; i<my_array.length; i++) {
   my_array[i].Project   // access the object project key
   my_array[i].Hours     // need to increment hours
}
3 Answers
Related