简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM