如何将单个数组中具有相同键的对象数组分组为对象?

时间:2016-11-30 18:25:08

标签: javascript arrays

我的数组是

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

我想要输出:

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

其他值相同

5 个答案:

答案 0 :(得分:1)

我通过迭代每个对象的键,并将键作为哈希值添加到您的值对象来解决此问题。

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

})

答案 1 :(得分:0)

这应该做你想要的:

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

答案 2 :(得分:0)

看起来你必须做一个循环才能得到你想要的东西。

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;

答案 3 :(得分:0)

您将遍历对象,并存储唯一结果。以下是对此进行编码的近似方法:

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

答案 4 :(得分:0)

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