I am looking to transform the following JSON structure
let data = {
item1: [11, 12, 13, 14, 15],
item2: [16, 17, 18, 19, 20]
}
into this specific format using JavaScript's native functionalities of arrays or objects (compatible with all web browsers)
[{
item1: 11,
item2: 16
},{
item1: 12,
item2: 17
},{
item1: 13,
item2: 18
},{
item1: 14,
item2: 19
},{
item1: 15,
item2: 20
}]
I attempted to achieve this using a for loop and here is the code snippet I came up with:
let keys = Object.keys(data);
let transformedData = [];
for(let i = 0; i < keys.length; i++){
let key = keys[i];
for(let j = 0; j < data[key].length; j++){
if(i === 0){
let obj1 = {};
obj1[key] = data[key][j];
transformedData.push(obj1);
}else{
let obj2 = transformedData[j];
obj2[key] = data[key][j];
}
}
}