Reputation: 6269
I have data that looks like this:
[{label: "uno", men: 3, kids: 2, womens: 5}, {label: "dos", men: 4, kids: 2, womens: 2}]
At the end of the transformation I would like to have 4 arrays containing the data-fields:
var labels = ["uno", "dos"];
var men = [3, 4];
var kids = [2, 2];
var womens = [5, 2];
I am doing it like that:
var label = [];
var men = [];
var kids = [];
var women = [];
dataArray.forEach(function(data){
label.push(data.label);
men.push(data.men);
kids.push(data.kids);
women.push(data.women);
});
Is there a nicer/shorter way to achieve the same data-transformation? Thanks a lot!
Upvotes: 1
Views: 43
Reputation: 859
You can do it in a generic way like
var arr = [{label: "uno", men: 3, kids: 2, womens: 5}, {label: "dos", men: 4, kids: 2, womens: 2}];
var outputData = {};
for(var i in arr) {
var element = arr[i];
for(var key in element) {
if(outputData.hasOwnProperty(key)) {
outputData[key].push(element[key]);
}
else {
outputData[key] = [element[key]];
}
}
}
console.log(outputData);
and for that you will get a result like
{
kids: [2, 2],
label: ["uno", "dos"],
men: [3, 4],
womens: [5, 2]
}
Upvotes: 0
Reputation: 386848
You could use an object for collecting and later assign the properties to the wanted variables.
This proposal iterates over all elements of the array and over all properties and build a new array if there is no key in the result object. Then add the value to the array.
var data = [{ label: "uno", men: 3, kids: 2, womens: 5 }, { label: "dos", men: 4, kids: 2, womens: 2 }],
result = {};
data.forEach(function (o) {
Object.keys(o).forEach(function (k) {
result[k] = result[k] || [];
result[k].push(o[k]);
});
});
console.log(result);
Upvotes: 2