I have two objects:
myObj1 = { "id": 1, "name": "Jason", "attributes":{"dob": "07/5/2021", "email": "jason@email.com"} };
myObj2 = { "id": 2, "name": "John", "attributes":{"dob": "07/5/2021", "email": ""} };
I would like to combine them into an object that looks like this:
myObj3 = { "name":{ 1: "Jason", 2: "John", comparison: "Different" }, "attributes": { "dob": { 1: "07/5/2021", 2: "07/5/2021", comparison: "identical" }, email: { 1: "jason@email.com", 2: "-", comparison: "missing" } } };
- Combines them into a single object
- iterates through and compares each of the attributes
- Adds the result of the comparison to the object
I found a few articles which use key value pairs which gets me some of the way but maybe there's a better way to do it?
// find keys
keyObj1 = Object.keys(myObj1);
keyObj2 = Object.keys(myObj2);
// find values
valueObj1 = Object.values(myObj1);
valueObj2 = Object.values(myObj2);
// find max length to iterate
if(keyObj1.length > keyObj2.length) {
var biggestKey = keyObj1.length;
} else {
var biggestKey = keyObj2.length;
}
// now compare their keys and values
for(var i=0; i<biggestKey; i++) {
if(keyObj1[i] == keyObj2[i] && valueObj1[i] == valueObj2[i]) {
console.log('same:' + valueObj2[i]);
} else {
// it prints keys have different values
console.log('different: '+ valueObj1[i] + '\ndifferent: '+ valueObj2[i] +'\n');
}
}