I have 2 arrays like this
const dates = ["2019", "2020", "2021"];
const data = [[100, 200, 300, 20], [400, 500, 600, 30], [700, 800, 900, 40]];
I want to merge these 2 arrays into an array of objects like this Details: The first object of the result array will have the values of the first element of each array in the 2d array The same goes with the rest of the result arrays
const result = [
{
2019: 100,
2020: 400,
2021: 700
},
{
2019: 200,
2020: 500,
2021: 800
},
{
2019: 300,
2020: 600,
2021: 900
},
{
2019: 20,
2020: 30,
2021: 40
}
]
I would recommend you first transpose your data rows then you can write table using Array.prototype.map and Object.fromEntries -
const transpose = t =>
t.some(a => Boolean(a.length))
? [t.map(a => a[0]), ...transpose(t.map(a => a.slice(1)))]
: []
const table = (columns, rows) =>
transpose(rows).map(r =>
Object.fromEntries(columns.map((c,i) =>
[c, r[i]]
))
)
const dates = ["2019", "2020", "2021"]
const data = [[100, 200, 300, 20], [400, 500, 600, 30], [700, 800, 900, 40]]
console.log(table(dates, data))
Maybe you can try this:
const dates = ["2019", "2020", "2021"];
const data = [[100, 200, 300, 20], [400, 500, 600, 30], [700, 800, 900, 40]];
const res=data[0].reduce((a,_,j,da)=>{
a.push(Object.fromEntries(dates.map((d,i)=>[d,data[i][j]])))
return a;
},[]);
console.log(res)