0

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)
    });
})

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.