sunnyn sunnyn - 3 days ago 5
Javascript Question

How to group an array of object with same key in a single array as object?

My Array is

[Object { Color="Blues", Shape="Octagon", Thickness="High (Over 1 Inch)", more...}, Object { Color="Burgundys", Shape="Oval", Thickness="3⁄8" (approx.)", more...}]


I want Output :

[{"Color":["Blues","Burgundys "],"Shape":['Octagon',"Oval"]}]


Same for others values

Answer

I'd approach this by iterating over the keys of each object, and adding the key as a hash to your values object.

var vals = {}
var src = [{ Color="Blues",  Shape="Octagon",  Thickness="High (Over 1 Inch)"}, { Color="Burgundys",  Shape="Oval",  Thickness="3⁄8 (approx.)"}]

src.forEach( function( obj ){

    for( var key in obj ){
        if( vals[ key ] === undefined ) 
            vals[ key ] = []

        vals[ key ].push( obj[ key ])
    }

})
Comments