Wednesday, 30 November 2016

Transforming an object with arrays into an array of objects with Javascript

This question was a lot of fun and I spent a happy 10 minutes figuring out how to transform the data. This seems to do the job:

var obj = {
    "pharmacy": [
        "Kroger Pharmacy"
    "price": [
}, data = [];

for(var i = 0; i < obj[Object.keys(obj)[0]].length; i++){
    var tempObject = {};
    for(var key in obj){
        tempObject[key] = obj[key][i];


I'm only putting it up here so I don't forget how to do it again if I need to do so. It's also worthwhile noting that the initial arrays need to be the same length or things could go really quite wrong.

No comments:

Post a Comment