sunnyn
sunnyn

Reputation: 9

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

Upvotes: 0

Views: 1952

Answers (5)

jusopi
jusopi

Reputation: 6813

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 ])
    }

})

Upvotes: 2

Joseph
Joseph

Reputation: 692

var arr = [{
  color: "Blues",
  Shape: "Octagon"
},
{
 color: "Burgundys",
 Shape="Oval"
}]

var targetObject = {};

for(var iloop=0; iloop< arr.length; iloop++){
  //get the keys in your object
  var objectKeys = Object.keys(arr[iloop]);

   //loop over the keys of the object
   for(var jloop=0; jloop<objectKeys.length; jloop++){
     //if the key is present in your target object push in the array 
     if( targetObject[ objectKeys[jloop] ] ){
       targetObject[objectKeys[jloop]].push( arr[iloop][objectKeys[jloop]] );
     }else{
       // else create a array and push inside the value
       targetObject[objectKeys[jloop]] = []
       targetObject[objectKeys[jloop]].push( arr[iloop][objectKeys[jloop]]     );
     }
   }
}

Upvotes: 0

31piy
31piy

Reputation: 23859

You will have too loop through the object, and store the unique results. Following is an approximate way to code this:

var colors = [], shapes = [];

for (var i = 0; i < object.length; i++) {
  var color = object[i].Color, shape = object[i].Shape;
  if (colors.indexOf(color) === -1) { colors.push(color); }
  if (shapes.indexOf(shape) === -1) { shapes.push(shape); }
}

result = {"Color": colors, "Shape": shapes};

Upvotes: 0

Daryl
Daryl

Reputation: 28

It looks like you will have to do a loop to get what you are looking for.

var colors = [];
var shapes = []; for(var i = 0;i<objArray.length;i++)
{
    colors[i] = objArray[i].color
    shapes[i] = objArray[i].shape
}
answer = {};
answer.colors = colors;
answer.shapes = shapes;

Upvotes: 0

fafl
fafl

Reputation: 7385

This should do what you want:

a = [{foo: 1, bar: 2}, {foo: 3, bar: 4}]
a.reduce((acc, val) => {
  for (var key in val) {
    if (!val.hasOwnProperty(key)) continue;
    if (!acc.hasOwnProperty(key)) acc[key] = []
    acc[key].push(val[key])
  }
  return acc
}, {})

Upvotes: 0

Related Questions