We have two JSON data which we would like to compare and get the difference between the values of two Keys , Count in First JSON data compared with AVG_X in JSON data .
First JSON-
var myObject=[
{
"Customer": "A",
"Count": 47
},
{
"Customer": "B",
"Count": 5
},
{
"Customer": "C",
"Count": 1
}
]
Second JSON-
var myobject1=[
{
"Customer": "A",
"AVG_X": 20
},
{
"Customer": "B",
"AVG_X": 4
},
{
"Customer": "C",
"AVG_X": 0
},
{
"Customer": "D",
"AVG_X": 3
}
]
Also the data size of First JSON is the length of the loop in which we need to iterate .
For that I am using this below function -
var key, count = 0;
for(key in myObject) {
if(myObject.hasOwnProperty(key)) {
count++;
}
}
Now to compare the values the of Count vs AVG_X and get the difference between these two for each Customer and save it in new JSON .
I am thinking around the below code but I am not 100% sure -
// find keys
keyObj1 = Object.keys(myObject);
keyObj2 = Object.keys(myObject1);
// find values
valueObj1 = Object.values(myObject);
valueObj2 = Object.values(myObject1);
// now compare their keys and values
for(var i=0; i<count; i++) {
if(keyObj1[i] == keyObj2[i] && valueObj1[i] == valueObj2[i]) {
console.log(valueObj2[i]);
}
else {
// it prints keys have different values
console.log('myObject1 value: '+ valueObj1[i] + '\nmyObject2 value: '+ valueObj2[i] +'\n');
}
}
};
Expected Output Should be something like below -
{
"Customer": "A",
"Diff": 27
},
{
"Customer": "B",
"Diff": 1
},
"Customer": "C",
"Diff": 1
}
Help would be much appreciated !!