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

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
does js comparison operator === works on json?
It will work...somewhat. let foo = { x: { y: { z: 100 } } } let bar = foo console.log(foo === bar) // true, because both variables point to the same object bar = { x: { y: { z: 100 } } } console.log(foo === bar) // false, bar now points to a different object, even if it's the same exact structure foo = JSON.stringify(foo) bar = JSON.stringify(bar) console.log(foo === bar) // true, we're essentially comparing strings now foo = JSON.parse(foo) bar = JSON.parse(bar) console.log(foo === bar) // false, back to pointing to different (new) objects More on reddit.com
๐ŸŒ r/learnjavascript
36
6
July 17, 2023
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
how to compare two deeply nested json objects?
If all you need is to check whether they equal or not, just do bytes.Equal . If you are looking for an accurate diff you can use testfy's JSON Equal here . More on reddit.com
๐ŸŒ r/golang
13
5
July 17, 2023
๐ŸŒ
GitHub
github.com โ€บ lukascivil โ€บ json-difference
GitHub - lukascivil/json-difference: A simple way to find the difference between two objects or json diff ยท GitHub
import { getDiff } from 'json-difference' const coffee = { color: { color1: 'black', color2: 'brown' }, special: true } const oil = { color: { color1: 'red', color2: 'blue' }, special2: false, especial3: [{}] } // Get JsonDiff delta const diff ...
Starred by 57 users
Forked by 5 users
Languages ย  TypeScript 91.8% | JavaScript 7.3% | HTML 0.9%
๐ŸŒ
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...
๐ŸŒ
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. JSON is a lightweight data-interchange structure commonly used to represent structured data.
Find elsewhere
๐ŸŒ
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 (npm library): This JavaScript package helps compare JSON objects and outputs differences. Itโ€™s widely used in Node.js environments. โ€ข Postman: A popular API testing tool that includes JSON comparison features.
๐ŸŒ
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: 11 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...
๐ŸŒ
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
json-diff - npm
diff({ outputNewOnly: true } โœ” should return only new diffs (added) โœ” should return only new diffs (changed) โœ” should return only new diffs (deleted) โœ” should return only old diffs - exchanged first and second json (added) โœ” should return only old diffs - exchanged first and second json (changed) โœ” should return only old diffs - exchanged first and second json (deleted) ... 1.0.1 Bug fixes: Properly compare date objects; properly exclude keys with -x; improve README readability. 1.0.0 Properly distinguish list elements with identical strings of different types e.g.
      ยป npm install json-diff
    
Published ย  May 15, 2023
Version ย  1.0.6
Author ย  Andrey Tarantsov
๐ŸŒ
Dykraf
dykraf.com โ€บ home โ€บ web development and seo blog โ€บ how to compare two json in javascript and react typescript
How To Compare Two Json In JavaScript And React TypeScript
February 1, 2024 - This is where users can compare information entered in the left-side form with that displayed in the right form and view the results in the table list. The UI was designed to offer the following users experiences: ... For the User Interface development, React.js and TypeScript were chosen as the libraries to handle the consumption and manipulation of JSON data objects, rendering them on the client-side browsers.
๐ŸŒ
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 - This JavaScript function provides a basic deep diffing mechanism, identifying additions, deletions, and modifications. It handles nested objects recursively. Note that comparing arrays deeply requires additional logic, which is simplified here for brevity (arrays are compared by value directly if they differ).
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ compare two json objects and get different javascript
Compare two JSON objects and get different JavaScript
April 19, 2024 - There is a library for getting the structural differences between two objects https://github.com/flitbit/diff ... function compareJSONObjects(obj1, obj2) { const keys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]); const differences ...
๐ŸŒ
ExtendsClass
extendsclass.com โ€บ json-diff.html
JSON diff - Online JSON Compare tool
Different value between the two JSON: highlight in red color ยท Element only presents in a single JSON: highlight in yellow color ... The last editor exclusively contains the diff between JSON. When a property differs, the difference contains the value of the first json. JSON, or JavaScript Object ...
๐ŸŒ
SamanthaMing
samanthaming.com โ€บ tidbits โ€บ 33-how-to-compare-2-objects
How to Compare 2 Objects in JavaScript ๐ŸŽ‰ | SamanthaMing.com
const one = { fruit: '๐Ÿฅ', nutrients: { energy: '255kJ', minerals: { name: 'calcium', }, }, }; const two = { fruit: '๐Ÿฅ', nutrients: { energy: '255kJ', minerals: { name: 'calcium', }, }, }; // Using JavaScript JSON.stringify(one) === JSON.stringify(two); // true // Using Lodash _.isEqual(one, two); // true ยท Well that depends. For JSON.stringify(), the order matters. So if the key-value pair are ordered differently in the two objects but are the same, it will return false. Whereas it doesn't matter in Lodash isEqual, it will return true as along as the key-value pair exists. Here's my recommendation. For a quick and dirty solution, I'd use JSON.stringify().
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];

 }
๐ŸŒ
@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.