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
}
]
CodePudding user response:
You can use Array.prototype.map and Object.fromEntries -
const table = (columns, rows) =>
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))
CodePudding user response:
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)
