Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

229
Views
Merge an array with a 2d array to an array of objects, with the keys are the elements of the 1d array

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
 }
]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!