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

152
Views
Make a new array objects using two different object in JavaScript

I have two objects. I am trying to do like :

var obj1 = {
 abc_name: "Jack", 
 abc_age: 24
}

var obj2 = {
 xyz_name: "Mike", 
 xyz_age: 22
}

Expected Output be like :

var obj = [{
 fieldName: "Name", 
 abc_name: "Jack", 
 xyz_name: "Mike"
}, 
{
 fieldName: "Age", 
 abc_age: 24, 
 xyz_age: 22
}]

I am trying with the nested for-in loop. But not getting expected results. Any better solution or idea ? Thanks in advance

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

One way to achieve this is Array.prototype.map:

const obj1 = {
 abc_name: "Jack", 
 abc_age: 24
}

const obj2 = {
 xyz_name: "Mike", 
 xyz_age: 22
}

const obj = Object.entries(obj1).map(([k, v]) => {
  const [, fieldname1] = k.split('_');
  const [prefix2] = Object.keys(obj2)[0].split('_');
  return {
    fieldname: fieldname1[0].toUpperCase() + fieldname1.substring(1),
    [k]: v,
    [prefix2 + '_' + fieldname1]: obj2[prefix2 + '_' + fieldname1]
  }
});

console.log(obj);

about 4 years ago · Santiago Gelvez Report

0

You could group by fieldName and get an array of collected key/value pairs.

const
    format = s => s[0].toUpperCase() + s.slice(1).toLowerCase(),
    obj1 = { abc_name: "Jack", abc_age: 24 },
    obj2 = { xyz_name: "Mike", xyz_age: 22 },
    result = Object.values([obj1, obj2].reduce((r, o) => {
        Object.entries(o).forEach(([k, v]) => {
            const fieldName = format(k.split('_')[1]);
            r[fieldName] ??= { fieldName };
            r[fieldName][k] = v;
        });
        return r;
    }, []));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Santiago Gelvez 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!