Last active
October 25, 2017 20:30
-
-
Save ttepasse/d96046d5db03b7d4094278d7393f300d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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