Vasuki Hebbar
Vasuki Hebbar

Reputation: 51

How to convert the object which contains multiple array into an array of objects in javascript?

Below object should be converted into an array of object. This is just a random problem statement. How to convert this to an array of objects? Please help.

// input 
objects={
    0:[1,2,3],
    1:["a","b","c"],
    2:["i","ii","iii"]
}

//expected output
objects2=[
    {0:1,1:"a",2:"i"},
    {0:2,1:"b",2:"ii"},
    {0:3,1:"c",2:"iii"}
]

Below code gives me only last entry mean [3,"c","iii"]

//tried solution
var res=[]
Object.keys(objects).forEach(k=>{
    // console.log(data[k])
    objects[k].forEach(element => {
        res[k]=element
        console.log(res)
    });
})

Upvotes: 0

Views: 124

Answers (2)

Donat
Donat

Reputation: 4813

Try the below code to do it in a functional way.

let objects = {
  0: [1, 2, 3],
  1: ["a", "b", "c"],
  2: ["i", "ii", "iii"]
};

function extend(obj, k, v) {
  if (!(k in obj)) obj[k] = [];
  obj[k].push(v);
  return obj;
} 

let result = Object.keys(objects).
  map(k => objects[k].map(v => [k, v])).           // convert to [key, value] pairs
  reduce((lst, elm) => lst.concat(elm)).           // flatten
  reduce((obj,[k, v]) => extend(obj, k, v), {});   // convert to objects
  
console.log(result);

Upvotes: 0

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

Try the below code.

let objects = {
  0: [1, 2, 3],
  1: ["a", "b", "c"],
  2: ["i", "ii", "iii"]
};

let objects2 = [];

//Fill the array with empty objects
for (object in objects) {
  objects2.push({});
}

//Fill the objects
for (const object in objects) {
  const values = objects[object];
  for (let i = 0; i < values.length; i++) {
    objects2[i][object] = values[i];
  }
}

console.log(objects2);

Upvotes: 1

Related Questions