1

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!

2
  • 1
    Your code is quite optimal Commented Jun 23, 2016 at 12:44
  • FYI, in JS all objects are hashes. Call them arrays, not hashes. Commented Jun 23, 2016 at 13:04

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Shorter? Maybe not. Nicer/more generic? Heck yes.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.