2014-09-25 14 views
7

Ho cercato di confrontare questi due oggetti JSON:Come confrontare due JSON hanno le stesse proprietà senza ordine?

<input type="hidden" id="remoteJSON" name="remoteJSON" value='{"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"}' /><br /> 
<input type="hidden" id="localJSON" name="localJSON" value='{"whoCanJoin": "CAN_REQUEST_TO_JOIN", "allowExternalMembers": "false"}' /><br /> 

ho ottenuto valori con javascript e ho cercato di confrontare con: JSON.stringify(remoteJSON) == JSON.stringify(localJSON) ma questo return false: cuciture che l'ordine delle proprietà è importante.

E anche in profondità confrontare con this solution e sempre ottenuto un ritorno falso.

C'è un modo rapido per risolvere il problema con jQuery (es. Librarie per confrontare JSON)?

+0

si dovrebbe leggere questo http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically –

+0

Could mostraci come stai provando il confronto profondo. –

+3

"e ha sempre un ritorno falso" --- no, non http://jsfiddle.net/pyLqhujo/ Se quella funzione restituisce 'false' significa letteralmente che i tuoi oggetti ** sono ** diversi. – zerkms

risposta

8

Lo Dash permette di farlo: http://lodash.com/docs#isEqual

violino solo per voi :) http://jsfiddle.net/L5qrfx3x/

var remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"}; 
var localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", "allowExternalMembers": "false"}; 

if(_.isEqual(remoteJSON, localJSON)){ 
    //TODO 
} 

Una libreria davvero potente. Esso contiene quasi tutto ciò che si può pensare

0

Questa domanda ricorda come determinare uguaglianza per due JavaScript oggetti. Quindi, avrei scelto this funzione generale

confronta gli oggetti JS:

function objectEquals(x, y) { 
    // if both are function 
    if (x instanceof Function) { 
     if (y instanceof Function) { 
      return x.toString() === y.toString(); 
     } 
     return false; 
    } 
    if (x === null || x === undefined || y === null || y === undefined) { return x === y; } 
    if (x === y || x.valueOf() === y.valueOf()) { return true; } 

    // if one of them is date, they must had equal valueOf 
    if (x instanceof Date) { return false; } 
    if (y instanceof Date) { return false; } 

    // if they are not function or strictly equal, they both need to be Objects 
    if (!(x instanceof Object)) { return false; } 
    if (!(y instanceof Object)) { return false; } 

    var p = Object.keys(x); 
    return Object.keys(y).every(function (i) { return p.indexOf(i) !== -1; }) ? 
      p.every(function (i) { return objectEquals(x[i], y[i]); }) : false; 
} 
+4

Quindi, in pratica hai appena copiato [questa risposta] (http: // stackoverflow.com/a/16788517/1338292)? –

+0

@ Ja͢ck: O hanno attribuito erroneamente. – BoltClock

+0

@BoltClock Anche se così fosse, questo non risponde alla domanda perché il problema non era nella funzione di confronto utilizzata. –

0

causa @zerkems commento:

dovrei convertire le mie corde per oggetto JSON e quindi chiamare il metodo uguale :

var x = eval("(" + remoteJSON + ')'); 
var y = eval("(" + localJSON + ')'); 

function jsonequals(x, y) { 
    // If both x and y are null or undefined and exactly the same 
    if (x === y) { 
     return true; 
    } 

    // If they are not strictly equal, they both need to be Objects 
    if (! (x instanceof Object) || ! (y instanceof Object)) { 
     return false; 
    } 

    // They must have the exact same prototype chain, the closest we can do is 
    // test the constructor. 
    if (x.constructor !== y.constructor) { 
     return false; 
    } 

    for (var p in x) { 
     // Inherited properties were tested using x.constructor === y.constructor 
     if (x.hasOwnProperty(p)) { 
      // Allows comparing x[ p ] and y[ p ] when set to undefined 
      if (! y.hasOwnProperty(p)) { 
       return false; 
      } 

      // If they have the same strict value or identity then they are equal 
      if (x[ p ] === y[ p ]) { 
       continue; 
      } 

      // Numbers, Strings, Functions, Booleans must be strictly equal 
      if (typeof(x[ p ]) !== "object") { 
       return false; 
      } 

      // Objects and Arrays must be tested recursively 
      if (!equals(x[ p ], y[ p ])) { 
       return false; 
      } 
     } 
    } 

    for (p in y) { 
     // allows x[ p ] to be set to undefined 
     if (y.hasOwnProperty(p) && ! x.hasOwnProperty(p)) { 
      return false; 
     } 
    } 
    return true; 
} 
+2

Don ' t usa 'eval()'; c'è 'JSON.parse()' o '$ .parseJSON()'. –

1

prima devi trasformare le stringhe in un oggetto reale prima chiamare equals():

var a = JSON.parse($('#remoteJSON').val()); 
var b = JSON.parse($('#localJSON').val()); 

console.log(equals(a, b)); 
+0

se sono in ordine diverso, questo approccio potrebbe non funzionare –

Problemi correlati