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

121
Views
2 Array combine into one array javascript

Here is two array one is firstName another is lastName

{
  firstName: ['name1', 'name2'],
  lastName: ['last1', 'last2'],
}

but I want to formate the data into one array like this.

{
  "name": [{
      "firstName": "name1",
      "lastName": "last1"
    },
    {
      "firstName": "name2",
      "lastName": "last2"
    },

  ]
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Using Array#map:

const getNameObj = (data = {}) => {
  const { firstName = [], lastName = [] } = data;
  if(firstName.length !== lastName.length) return;
  const name = firstName.map((fn, i) => (
    { firstName: fn, lastName: lastName[i] }
  ));
  return { name };
};

console.log( 
  getNameObj({ firstName: [ 'name1', 'name2' ], lastName: [ 'last1', 'last2' ] })
);

about 4 years ago · Juan Pablo Isaza Report

0

You could loop through it using for...in and push each element inside new array like this example

const data = {
 firstName: [ 'name1', 'name2' ],
 lastName: [ 'last1', 'last2' ],
}

let newData = [];

for (let el in data.firstName){
  newData.push({
    firstName: data.firstName[el],
    lastName: data.lastName[el],
  })  
}

console.log(newData)

about 4 years ago · Juan Pablo Isaza Report

0

You can use Array.reduce to get the result.

const input = {
    firstName: [ 'name1', 'name2' ],
    lastName: [ 'last1', 'last2' ],
};

const result = input.firstName.reduce((acc, firstName, index) => {
   acc.name.push({
     firstName: firstName,
     lastName: input.lastName[index]
   })
   return acc
}, {'name': []})

console.log(result);

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!