0

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 !!

dream123
  • 41
  • 7
  • 1
    what is your expected result? – DecPK Jun 01 '21 at 08:29
  • @decpk Expected Output would be something like this , { "Customer": "A", "Diff": 27 }, { "Customer": "B", "Diff": 1 }, "Customer": "C", "Diff": 1 } – dream123 Jun 01 '21 at 08:36
  • [That is JavaScript, not JSON](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Quentin Jun 01 '21 at 08:37
  • @here To me this question is unique ,the answer in the question https://stackoverflow.com/questions/21987909/how-to-get-the-difference-between-two-arrays-of-objects-in-javascript doesn't solve my queries . – dream123 Jun 01 '21 at 09:02

0 Answers0