Skip to content

Instantly share code, notes, and snippets.

@AdventureBear
Created May 25, 2015 16:31
Show Gist options
  • Save AdventureBear/7a51c7801b9719b76349 to your computer and use it in GitHub Desktop.
Save AdventureBear/7a51c7801b9719b76349 to your computer and use it in GitHub Desktop.
Pivot Object into new Arrays Dynamically via @ekojsalim @free Code Camp
var obj = [
{
"name": "Free Code Camp",
"cost": 0,
"weeks": 18,
"location": "online"
},
{
"name": "Costly Code Camp",
"cost": 20000,
"weeks": 12,
"location": "Chicago"
},
{
"name": "Boring Camp Coders",
"cost": 5000,
"weeks": 20,
"location": "Panama"
},
];
// I want my array to look like this:
// [ { names: ['Free Code Camp', 'Costly Code Camp', 'Boring Code Camp'] },
// { weeks: [18, 12, 20] },
// { cost: [0, 20000, 5000] } ]
function repIt() {
var args = Array.prototype.slice.call(arguments);
var out = [];
for(var i = 0; i< args.length; i++) {
var p = args[i];
out[i] = {};
out[i][p] = [];
}
for(var j = 0; j < obj.length; j++) {
for(var x = 0; x < out.length; x++) {
out[x][args[x]].push(obj[j][args[x]]);
}
}
console.log(out);
}
repIt("name","location","weeks");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment