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

112
Views
How to make an array of object from 2 arrays

Let's say I have any array like:

a = ["name", "age"] and then an array of arrays like b = [["Alex", 20], ["Ari", 25], ..] I want to make an array of object that get its keys from a and values from b

[{
  name: "Alex",
  age: 20
}, 
{
  name: "Ari",
  age: 25
}]

I tried the following:

for (const arr of b) {
  Object.assign({}, arr)
}

which makes an object but doesn't use keys of array a.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

const a = ["name", "age"]
const b = [["Alex", 20], ["Ari", 25]]

const output = b.map(item => {
 return a.reduce((aggr, curr, i) => (aggr[curr] = item[i], aggr), {});
});

console.log(output);

However the code assumes the length of a always matches length of each item in b. Make sure to guard it properly.

In case you were pondering about the statement in parentheses (aggr[curr] = item[i], aggr), this is JavaScript's comma operator which executes all comma-delimited statements and returns the value of the last one - in this case aggr (which we need to return for next iteration of .reduce to aggregate the object).

about 4 years ago · Juan Pablo Isaza Report

0

If you want something in Python you can also try this.

my_list = []
a = ['name','age']
b = [['alex', 20], ['ari', 25], ['pete', 45], ['alf', 67]]

for person in b:
    temp = {}
    for i in range(len(a)):
        temp[a[i]] = person[i]
    my_list.append(temp)
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!