Reputation: 9
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
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
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
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
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
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