Skip to content

Instantly share code, notes, and snippets.

@ttepasse
Last active October 25, 2017 20:30
Show Gist options
  • Save ttepasse/d96046d5db03b7d4094278d7393f300d to your computer and use it in GitHub Desktop.
Save ttepasse/d96046d5db03b7d4094278d7393f300d to your computer and use it in GitHub Desktop.
var thing = {x: [0, 1, 2], y: [3, 4, 5]};
function transform (thing) {
let keys = Object.keys(thing) // ["x", "y"]
let values = Object.values(thing) // [[0, 1, 2], [3, 4, 5]]
let count = values[0].length
if( !values.every(subarray => subarray.length == count)) {
throw "Sub-Arrays aren't the same length"
}
var out = []
for (var index = 0; index != count; index++) {
// [[0, 1, 2], [3, 4, 5]] → [0, 3] with index=0
let value = values.map(subarray => subarray[index])
let obj = keys.reduce(function (obj, key, index) {
obj[key] = value[index]
return obj
}, {})
out.push(obj)
}
return out
};
console.log(transform(thing))
// [{x: 0, y: 3}, {x: 1, y: 4}, {x: 2, y: 5}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment