2

I have 2 json arrays as below and I will do an jQuery extend later. I would like to use jQuery and compare only all elements (a,b) from array1 against array2, to check whether the (a,b) exists in array2 and get the difference if exists.

I have tried the code as below but somehow I always got the unexpected console output as actual return below. I would appreciate for any advice.

var array1 = {a: "AT", b: "1000"};
var array2 = {c: 0, d: 100, a: "AT", b: "1002"};
console.log($(array1).not(array2).get());

Expected return:

[Object]
    0: Object
    b: "1000"
    __proto__: Object
    length: 1
    __proto__: Array[0]

Actual return:

[Object]
    0: Object
    a: "AT"
    b: "1000"
    __proto__: Object
    length: 1
    __proto__: Array[0]
SƲmmēr Aƥ
  • 2,374
  • 6
  • 24
  • 29
  • i already post the answer for same situation. here is the link that may help u and others. http://stackoverflow.com/questions/8108666/jquery-javascript-json-object-comparison/28604389#28604389 – Mou Feb 19 '15 at 10:53

1 Answers1

3

I have refer to the link below and modify the given answer accordingly. The modified answer as below.

References: Compare two JSON arrays in JQuery or Javascript

Modified Answer:

var origArrayGroups = {c: 0, d: 100, a: "AT", b: "1002"};
var userArrayGroups = {a: "AT", b: "1000"};

var diff = {};
for (var prop in userArrayGroups) {
    console.log("Comparing element: " + prop);
    if(userArrayGroups[prop] != origArrayGroups[prop])
    {
        diff[prop] = origArrayGroups[prop];
        console.log("Result: " + userArrayGroups[prop] + "!=" + origArrayGroups[prop]);
    }
    else
    {console.log("Result: " + userArrayGroups[prop] + "==" + origArrayGroups[prop]);}

}

console.log(diff);

Actual Return:

Object {b: "1002"} 
Community
  • 1
  • 1
SƲmmēr Aƥ
  • 2,374
  • 6
  • 24
  • 29