简体   繁体   中英

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

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

})

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
}, {})

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM