Merge objects with the same key in javascript

I tried to figure this out for a long time, if I have an array of such objects:

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 combine all the objects with the same key together into one object, so that their time adds up:

Expected Result:

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

How can I approach this problem? It took me a long time for my data to be formatted in this way, this is the last step!

My attempt, I understand that I am sorting through an array, I don’t know how to deal with merging 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
}
+4
source share
3 answers

In your attempt, you cannot create a new array

var newArray = [];
var uniqueprojects = {};
for (var i =0; i<my_array.length; i++) {

   if ( !uniqueproject[my_array[i].Project] )
   {
     uniqueproject[my_array[i].Project] = 0;
   }
   uniqueproject[my_array[i].Project] += my_array[i].Hours;
   //my_array[i].Project   // access the object project key
   //my_array[i].Hours     // need to increment hours
}

uniqueproject

newArray = Object.keys(uniqueproject).map(function(key){return {Project:key, Hours:uniqueproject[key]}});
+2

, ,

var groups = my_array.reduce(function(resultObject, currentObject) {

    // if this is the first time the project appears in the array, use zero as the
    // default hours
    resultObject[currentObject.Project] = resultObject[currentObject.Project] || 0;

    // add the current hours corresponding to the project
    resultObject[currentObject.Project] += currentObject.Hours;

    return resultObject;
}, {});

groups :

console.log(groups);
// { A: 8, B: 3, C: 14 }

,

var result = Object.keys(groups).map(function(currentGroup) {
    return {Project: currentGroup, Hours: groups[currentGroup]};
});

[ { Project: 'A', Hours: 8 },
  { Project: 'B', Hours: 3 },
  { Project: 'C', Hours: 14 } ]
+7

thefourtheye gurvinder372 , jsPerf, , , .

, gurvinder372 .

P.S. , Uncaught TypeError, jsPerf, , . . this this.

+2

All Articles