Q:

Convert array of object to another array of object using jQuery

I am getting a result in my JavaScript file which I want to convert into another object.
My original result
 results=[{Key1:'Value1',Key2:100,Key3:'A'},
             {Key1:'Value1',Key2:40,Key3:'B'},
             {Key1:'Value2',Key2:60,Key3:'A'},
             {Key1:'Value2',Key2:70,Key3:'B'},
             {Key1:'Value3',Key2:50,Key3:'A'},
             {Key1:'Value3',Key2:90,Key3:'B'}];

Convert this to look like array of objects using jQuery or JavaScript. How can I achieve this?
finalResult=[{Key1:'Value1',A:100,B:40},
             {Key1:'Value2',A:60,B:70},
             {Key1:'Value3',A:50,B:90}];

Needed help in this

A:

You are initializing the array incorrectly, you need to replace outer () by [], like
var results = [ {}, {} ];

You need to first make a map of different Key1's
var map = {};
results.forEach( function(item){
   map[ item.Key1 ] = map[ item.Key1 ] || {};
   map[ item.Key1 ][ item.Key3 ] = map[ item.Key1 ][ item.Key3 ] || 0;
   map[ item.Key1 ][ item.Key3 ] += item.Key2;
})

Now iterate the keys of this map, and prepare your output
var output = Object.keys(map).map( function(value){ 
    var obj = { key1 : value }; 
    Object.keys( map[ value ] ).forEach( function(key2){ 
        obj[ key2 ] = map[ value ][ key2 ] 
    }); 
    return obj;  
});

Demo

var results=[
  {Key1:'Value1',Key2:100,Key3:'A'},
  {Key1:'Value1',Key2:40,Key3:'B'},
  {Key1:'Value2',Key2:60,Key3:'A'},
  {Key1:'Value2',Key2:70,Key3:'B'},
  {Key1:'Value3',Key2:50,Key3:'A'},
  {Key1:'Value3',Key2:90,Key3:'B'}
];
var map = {};
results.forEach( function(item){
   map[ item.Key1 ] = map[ item.Key1 ] || {};
   map[ item.Key1 ][ item.Key3 ] = map[ item.Key1 ][ item.Key3 ] || 0;
   map[ item.Key1 ][ item.Key3 ] += item.Key2;
});

var output = Object.keys(map).map( function(value){ 
    var obj = { key1 : value }; 
    Object.keys( map[ value ] ).forEach( function(key2){ 
        obj[ key2 ] = map[ value ][ key2 ] 
    }); 
    return obj;  
});
console.log( output );

