It's possible to use a recursive function that iterates by the object keys. Then use the Object.is to test for NaN and null. Then test if the second object is the type that cast to false like 0, NaN, or null. List the keys of both objects and concatenate them to test of missing keys in the obj1 and then iterate it.

When there is a difference between the same key values, it stores the value of object2 and proceeds. If both key values are object means that can be recursively compared and so it does.

function diff(obj1, obj2) {
    const result = {};
    if (Object.is(obj1, obj2)) {
        return undefined;
    }
    if (!obj2 || typeof obj2 !== 'object') {
        return obj2;
    }
    Object.keys(obj1 || {}).concat(Object.keys(obj2 || {})).forEach(key => {
        if(obj2[key] !== obj1[key] && !Object.is(obj1[key], obj2[key])) {
            result[key] = obj2[key];
        }
        if(typeof obj2[key] === 'object' && typeof obj1[key] === 'object') {
            const value = diff(obj1[key], obj2[key]);
            if (value !== undefined) {
                result[key] = value;
            }
        }
    });
    return result;
}

The code above is BSD licensed and can be used anywhere.

Test link: https://jsfiddle.net/gartz/vy9zaof2/54/

An important observation, this will convert arrays to objects and compare the values in the same index position. There are many other ways to compare arrays not covered by this function due to the required extra complexity.

EDIT 2/15/2019: This answer was changed to add the new ES2017 syntax and fix use-cases from comments.


This is just a kickoff, I haven't tested it, but I began with a filter or comparator function, that is recursive, change it however you need to get priority results.

function filter(obj1, obj2) {
    var result = {};
    for(key in obj1) {
        if(obj2[key] != obj1[key]) result[key] = obj2[key];
        if(typeof obj2[key] == 'array' && typeof obj1[key] == 'array') 
            result[key] = arguments.callee(obj1[key], obj2[key]);
        if(typeof obj2[key] == 'object' && typeof obj1[key] == 'object') 
            result[key] = arguments.callee(obj1[key], obj2[key]);
    }
    return result;
}

Tests: http://jsfiddle.net/gartz/Q3BtG/2/

Answer from Gabriel Gartz on Stack Overflow
🌐
JSON Diff
jsondiff.com
JSON Diff - The semantic JSON compare tool
Validate, format, and compare two JSON documents. See the differences between the objects instead of just the new lines and mixed up properties.
Top answer
1 of 9
63

It's possible to use a recursive function that iterates by the object keys. Then use the Object.is to test for NaN and null. Then test if the second object is the type that cast to false like 0, NaN, or null. List the keys of both objects and concatenate them to test of missing keys in the obj1 and then iterate it.

When there is a difference between the same key values, it stores the value of object2 and proceeds. If both key values are object means that can be recursively compared and so it does.

function diff(obj1, obj2) {
    const result = {};
    if (Object.is(obj1, obj2)) {
        return undefined;
    }
    if (!obj2 || typeof obj2 !== 'object') {
        return obj2;
    }
    Object.keys(obj1 || {}).concat(Object.keys(obj2 || {})).forEach(key => {
        if(obj2[key] !== obj1[key] && !Object.is(obj1[key], obj2[key])) {
            result[key] = obj2[key];
        }
        if(typeof obj2[key] === 'object' && typeof obj1[key] === 'object') {
            const value = diff(obj1[key], obj2[key]);
            if (value !== undefined) {
                result[key] = value;
            }
        }
    });
    return result;
}

The code above is BSD licensed and can be used anywhere.

Test link: https://jsfiddle.net/gartz/vy9zaof2/54/

An important observation, this will convert arrays to objects and compare the values in the same index position. There are many other ways to compare arrays not covered by this function due to the required extra complexity.

EDIT 2/15/2019: This answer was changed to add the new ES2017 syntax and fix use-cases from comments.


This is just a kickoff, I haven't tested it, but I began with a filter or comparator function, that is recursive, change it however you need to get priority results.

function filter(obj1, obj2) {
    var result = {};
    for(key in obj1) {
        if(obj2[key] != obj1[key]) result[key] = obj2[key];
        if(typeof obj2[key] == 'array' && typeof obj1[key] == 'array') 
            result[key] = arguments.callee(obj1[key], obj2[key]);
        if(typeof obj2[key] == 'object' && typeof obj1[key] == 'object') 
            result[key] = arguments.callee(obj1[key], obj2[key]);
    }
    return result;
}

Tests: http://jsfiddle.net/gartz/Q3BtG/2/

2 of 9
11

contributing back my changes to Gabriel Gartz version. This one works in strict mode and removes the array check - will always be false. It also removes empty nodes from the diff.

//http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
var isEmptyObject = function(obj) {
    var name;
    for (name in obj) {
        return false;
    }
    return true;
};

//http://stackoverflow.com/questions/8431651/getting-a-diff-of-two-json-objects
var diff = function(obj1, obj2) {
    var result = {};
    var change;
    for (var key in obj1) {
        if (typeof obj2[key] == 'object' && typeof obj1[key] == 'object') {
            change = diff(obj1[key], obj2[key]);
            if (isEmptyObject(change) === false) {
                result[key] = change;
            }
        }
        else if (obj2[key] != obj1[key]) {
            result[key] = obj2[key];
        }
    }
    return result;
};
Discussions

javascript - How to compare two JSON have the same properties without order? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
javascript - Compare Two Json object's value, Find the Difference of objects's value and ouptut to new Json - Stack Overflow
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=[ ... More on stackoverflow.com
🌐 stackoverflow.com
June 1, 2021
javascript - Compare two JSON objects and just return another JSON object with only the changes - Stack Overflow
I am new to JavaScript and trying to find the difference between two JSON Objects. The structure of the JSON object and its data is shown below. I got a code online which works for a normal JSON ob... More on stackoverflow.com
🌐 stackoverflow.com
Is there a library that allows to easily do diffchecks between two json?
I mean, you could stringify them both and check if they are equal or not… would be a quick and dirty way. More on reddit.com
🌐 r/reactjs
27
16
October 13, 2022
People also ask

What types of comparisons does JSDiff support?
JSDiff supports multiple comparison modes: JSON (semantic comparison), Characters, Words, Lines, and Patch format. Each mode is optimized for different use cases.
🌐
json.jsdiff.com
json.jsdiff.com › home
JSON Diff - The semantic JSON compare tool - JavaScript Text Diff ...
What is JSDiff?
JSDiff is a free online tool for comparing JSON and JavaScript code. It uses the Myers Difference Algorithm to highlight differences between two text segments, making it easy to see what has been added, removed, or modified.
🌐
json.jsdiff.com
json.jsdiff.com › home
JSON Diff - The semantic JSON compare tool - JavaScript Text Diff ...
Is my data safe when using JSDiff?
Yes, all data processing happens locally in your browser. No data is sent to any server, ensuring complete privacy and security.
🌐
json.jsdiff.com
json.jsdiff.com › home
JSON Diff - The semantic JSON compare tool - JavaScript Text Diff ...
🌐
GitHub
gist.github.com › 95c58862f54cee57ae68e58bee2378f2
Compare two JSON Objects and get Difference. · GitHub
Compare two JSON Objects and get Difference. GitHub Gist: instantly share code, notes, and snippets.
🌐
Quora
quora.com › How-can-I-compare-two-JSON-objects-with-their-key-value-pairs-using-JavaScript
How to compare two JSON objects with their key-value pairs using JavaScript - Quora
Answer (1 of 6): There are actually a couple of ways to do this, and it depends on the type of data you have. If you've a JSON format set, like a particular API endpoint returning JSON, and you want to compare the same structure for a possible change in values, you can directly convert both payl...
🌐
EyeHunts
tutorial.eyehunts.com › home › compare two json objects and get different javascript
Compare two JSON objects and get different JavaScript
April 19, 2024 - Simple run a for loop over the first JSON object and check whether the second one has it or not to Compare two JSON objects and get different JavaScript.
🌐
Json-format
json-compare.json-format.com › home › uncategorized › how to compare two json objects and get difference and get their differences effectively
How to compare two json objects and get difference and Get Their Differences Effectively - online json comparator
January 24, 2026 - JavaScript doesn’t have a built-in deep comparison or diffing function for objects. You often need to implement one or use a library. For a custom solution, we can write a recursive function.
Find elsewhere
🌐
JSON Formatter
jsonformatter.org › json-compare
JSON Compare Online to find different between two json
JSON Compare refers to the process of comparing two JSON (JavaScript Object Notation) data structures to determine the differences between them.
🌐
Baeldung
baeldung.com › home › json › jackson › compare two json objects with jackson
Compare Two JSON Objects with Jackson | Baeldung
January 8, 2024 - Learn how to use Jackson to compare two JSON objects using the built-in comparator and a custom comparator
🌐
JSDiff
json.jsdiff.com › home
JSON Diff - The semantic JSON compare tool - JavaScript Text Diff Library | Myers Algorithm Implementation
Validate, format, and compare two JSON documents. See the differences between the objects instead of just the new lines and mixed up properties.
🌐
ExtendsClass
extendsclass.com › json-diff.html
JSON diff - Online JSON Compare tool
JSON diff tool makes a semantic comparison, it compares every attribute–value pairs of objects. It compares each element according to their position in the arrays.
Top answer
1 of 2
1

Just map over the myObject and get the difference and store the result in a new object with properties Customer and Diff.

If the object with same Customer in both array

var myObject = [
  { Customer: "A", Count: 47 },
  { Customer: "B", Count: 5 },
  { Customer: "C", Count: 1 },
];

var myobject1 = [
  { Customer: "A", AVG_X: 20 },
  { Customer: "B", AVG_X: 4 },
  { Customer: "C", AVG_X: 0 },
  { Customer: "D", AVG_X: 3 },
];

const result = myObject.map((o, i) => ({
  Customer: o.Customer,
  Diff: o.Count - myobject1[i].AVG_X,
}));

console.log(result);

If the object can be present in any position in myobject1

var myObject = [
  { Customer: "A", Count: 47 },
  { Customer: "B", Count: 5 },
  { Customer: "C", Count: 1 },
];

var myobject1 = [
  { Customer: "A", AVG_X: 20 },
  { Customer: "B", AVG_X: 4 },
  { Customer: "C", AVG_X: 0 },
  { Customer: "D", AVG_X: 3 },
];

const result = myObject.map((obj) => {
  const { Customer, Count } = obj;
  const isExist = myobject1.find((o) => o.Customer === Customer);
  if (isExist) return { Customer, Diff: Count - isExist.AVG_X };
  else return obj;
});

console.log(result);

2 of 2
1

var myObject=[
  {
    "Customer": "A",
    "Count": 47
  },
  {
    "Customer": "B",
    "Count": 5
  },
  {
    "Customer": "C",
    "Count": 1
  }
];

var myobject1=[
  {
    "Customer": "A",
    "AVG_X": 20
  },
  {
    "Customer": "B",
    "AVG_X": 4
  },
  {
    "Customer": "C",
    "AVG_X": 0
  },
  {
    "Customer": "D",
    "AVG_X": 3
  }
];

let myobject1_customer_array = myobject1.map(a => a.Customer);

let result = [];
let myobject1_id;

for(var i = 0; i < myObject.length; i++) {

  myobject1_id = myobject1_customer_array.indexOf(myObject[i].Customer);

  if (myobject1_id != -1) {
    
    result.push({
      "Customer": myObject[i].Customer,
      "Diff": Math.abs(myObject[i].Count - myobject1[myobject1_id].AVG_X)
    })
  }
}

console.log(result);

Top answer
1 of 2
9

You can try following as a simple comparison:

Note: This answer assumes the structure to be exactly same. You can take this as reference and make it more generic for cases where structures are different.

Points to consider:

  • Number of items are different. o1.details have 2 entries and o2.details have say 5 entries.
  • Object structure is different. Properties in both object are different.

function getDifference(o1, o2) {
  var diff = {};
  var tmp = null;
  if (JSON.stringify(o1) === JSON.stringify(o2)) return;

  for (var k in o1) {
    if (Array.isArray(o1[k]) && Array.isArray(o2[k])) {
      tmp = o1[k].reduce(function(p, c, i) {
        var _t = getDifference(c, o2[k][i]);
        if (_t)
          p.push(_t);
        return p;
      }, []);
      if (Object.keys(tmp).length > 0)
        diff[k] = tmp;
    } else if (typeof(o1[k]) === "object" && typeof(o2[k]) === "object") {
      tmp = getDifference(o1[k], o2[k]);
      if (tmp && Object.keys(tmp) > 0)
        diff[k] = tmp;
    } else if (o1[k] !== o2[k]) {
      diff[k] = o2[k]
    }
  }
  return diff;
}

var o1={id:"1",details:[{name:"Peter",address:"Arizona",phone:9900998899},{name:"Jam",address:"Kentucky",phone:56034033343}],profession:"Business"},
o2={id:"2",details:[{name:"Peter",address:"Arizona",phone:9900998899},{name:"David",address:"Boston",phone:434323434}],profession:"Business"};

var d = getDifference(o1, o2)
console.log(d)

I had written an answer to detect changes in objects. You can even take reference from this as well.

2 of 2
0

You need to run a for loop over the first object and check whether the second one has it or not. Then save it to a new third object:

 var obj3={};
 for (var key in obj1)
 {
    !obj2.hasOwnProperty(key) && obj3[key]=obj[key];

 }
🌐
JSON Editor Online
jsoneditoronline.org › home › compare › json-compare
JSON compare: how to compare two JSON files? | Indepth
January 18, 2023 - In JavaScript, you can for example use the lodash function isEqual, which is very fast. This function iterates recursively over the two objects and checks for every property and item whether the left and right side is equal.
🌐
npm
npmjs.com › package › json-diff-ts
json-diff-ts - npm
2 weeks ago - Modern TypeScript JSON diff library - Zero dependencies, high performance, ESM + CommonJS support. Calculate and apply differences between JSON objects with advanced features like key-based array diffing, JSONPath support, and atomic changesets.. Latest version: 4.10.0, last published: 13 days ago.
      » npm install json-diff-ts
    
Published   Mar 06, 2026
Version   4.10.0
Author   Christian Glessner
🌐
Quora
quora.com › How-do-you-compare-two-JSON-objects-in-JavaScript-or-jQuery-and-delete-the-matching-key-value-pairs
How to compare two JSON objects in JavaScript or jQuery and delete the matching key value pairs - Quora
Answer (1 of 3): [code]// Set up our objects. const objOne = { "aKey": "1", "bKey": "2", "cKey": "5" }; const objTwo = { "aKey": "4", "zKey": "286" }; //Get the keys of each object. const keySetOne = Object.keys(objOne); const keySetTwo = Object.keys(objTwo); // Loop through the first set of ke...
🌐
@url-decode.com
url-decode.com › tool › json-diff
JSON Diff - Best Online JSON Compare Tool - URL Decoder
Use this JSON Diff tool to validate, format, and compare two JSON documents. Upload JSON code, compare, and find differences between two JSON objects.
🌐
DEV Community
dev.to › keploy › diff-json-a-complete-guide-to-comparing-json-data-3e31
Diff JSON – A Complete Guide to Comparing JSON Data - DEV Community
October 15, 2024 - JSON Diff Tools and Libraries ... JSON data. It can filter, query, and compare JSON directly in the terminal. • JSON-diff (npm library): This JavaScript package helps compare JSON objects and outputs difference...