I have an object, Object1
which is the Datamodel for AngularForms Where all the Form functionality has been built using this Model and changing the model is not feasible at this stage.
An Api is requesting the data in format of Object2
, to send the data to API I have to copy all the data in Object1
to Object2
.
The two objects are as below: just a sample on how different two objects are
object1 = {
applicant: {
name : "Abc",
title : "Mr.",
addr1 : "",
addr2 : "",
email : "someone@example.com"
},
nominee: {
name : "Def",
title : "Ms.",
addr1 : "",
email : "sometwo@example.com",
mobile : ""
},
...
}
and
object2 = {
"key1_1": "Abc",
"key1_2": "Mr.",
"key1_3": "",
"key1_4": "",
"key1_5": "someone@example.com",
"key2_1": "Def",
"key2_2": "Ms.",
"key2_3": "",
"key2_4": "sometwo@example.com",
"key2_5": "",
...
}
I want to able to convert from 1st Object to 2nd Object.I have written function
as below. So, calling the function and passing the Object1 as param return Object2 and vice versa.
function convertToObj2(object1){
obj2 = {
key1_1 : object1.applicant.name,
key1_2 : object1.applicant.title,
key1_3 : object1.applicant.addr1,
key1_4 : object1.applicant.addr2,
key1_5 : object1.applicant.email,
key2_1 : object1.nominee.name,
key2_2 : object1.nominee.title,
key2_3 : object1.nominee.addr1,
key2_4 : object1.nominee.email,
key2_5 : object1.nominee.mobile,
...
}
return obj2;
}
function convertToObj1(object2){
obj1 = {
applicant: {
name : object2.key1_1,
title : object2.key1_2,
addr1 : object2.key1_3,
addr2 : object2.key1_4,
email : object2.key1_5
},
nominee: {
name : object2.key2_1,
title : object2.key2_2,
addr1 : object2.key2_3,
email : object2.key2_4,
mobile : object2.key2_5
},
...
}
return obj1;
}
Is there a better way to map these objects to each other, without manually assigning each value to the key, as it is tedious and each object contains 300+ keys?
Note: names of keys are not as shown in exapmle, they are normal words without undersorce and not in alpha order.