简体   繁体   中英

Compare two json objects

suppose to have 2 json object like this :

 var obj1=    {
"errors":{
  "addcreditcard":"Non è stato possibile associare questa carta, ti preghiamo di ricontrollare i dati e riprovare.",
  "creditrecharge":"Si è verificato un errore durante la ricarica.",
  "ticketvalidation":"Siamo spiacenti, si è verificato un problema durante la validazione.",
  "ticketpurchase": "Siamo spiacenti, si è verificato un problema durante l\"acquisto.",
  "qrwrong": "Hai scansionato un QR Code non valido. Scansiona un QR Code OpenMove."
 }
}

And this :

var obj2 =  {
'errors':{
   'addcreditcard':'Wir konnten diese Karte nicht verifizieren. Bitte         \u00fcberpr\u00fcfe deine Angaben und versuche es noch einmal.',
   'creditrecharge':'Beim Aufladen deines Guthabens ist ein Fehler aufgetreten.',
   'qrwrong': 'Sie haben einen ung\u00fcltigen QR Code gescannt. Bitte einen OpenMove QR Code scannen.'
}
}

How can I get another object (using javascript or jquery) with the values in the first json but not in the second? In this case it will be :

 var example = {
  "errors":{
      "ticketvalidation":"Siamo spiacenti, si è verificato un problema durante  la validazione.",
     "ticketpurchase": "Siamo spiacenti, si è verificato un problema durante l\"acquisto."
}
}

You can use this code that iterates over all properties in the second object and checks if they exist in the first one:

   var obj1=    {
"errors":{
  "addcreditcard":"Non è stato possibile associare questa carta, ti preghiamo di ricontrollare i dati e riprovare.",
  "creditrecharge":"Si è verificato un errore durante la ricarica.",
  "ticketvalidation":"Siamo spiacenti, si è verificato un problema durante la validazione.",
  "ticketpurchase": "Siamo spiacenti, si è verificato un problema durante l\"acquisto.",
  "qrwrong": "Hai scansionato un QR Code non valido. Scansiona un QR Code OpenMove."
 }
};

 var obj2 =  {
'errors':{
   'addcreditcard':'Wir konnten diese Karte nicht verifizieren. Bitte         \u00fcberpr\u00fcfe deine Angaben und versuche es noch einmal.',
   'creditrecharge':'Beim Aufladen deines Guthabens ist ein Fehler aufgetreten.',
   'qrwrong': 'Sie haben einen ung\u00fcltigen QR Code gescannt. Bitte einen OpenMove QR Code scannen.'
}
};

var finalObject = {};
for (var property in obj1.errors) {

    if (obj1.errors.hasOwnProperty(property)) {

       if(!obj2.errors.hasOwnProperty(property)){

           // exist only in first
           finalObject[property] = obj1.errors[property];
       }
    }
}

console.log(finalObject)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM