Home > Software design >  Make a new array objects using two different object in JavaScript
Make a new array objects using two different object in JavaScript

Time:12-10

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

CodePudding user response:

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

CodePudding user response:

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; }

  • Related