It's not too hard to create a function like this. Just loop through each field in the second object, and if it's not present in the first or the value is different than the first, put that field in the return object.

var compareJSON = function(obj1, obj2) {
  var ret = {};
  for(var i in obj2) {
    if(!obj1.hasOwnProperty(i) || obj2[i] !== obj1[i]) {
      ret[i] = obj2[i];
    }
  }
  return ret;
};

You can see it in action on this demo page.

Answer from Peter Olson on Stack Overflow
🌐
npm
npmjs.com › package › json-diff
json-diff - npm
% json-diff --help Usage: json-diff [-vCjfonskKp] first.json second.json Arguments: <first.json> Old file <second.json> New file General options: -v, --verbose Output progress info -C, --[no-]color Colored output -j, --raw-json Display raw JSON encoding of the diff -f, --full Include the equal sections of the document, not just the deltas --max-elisions COUNT Max number of ...s to show in a row in "deltas" mode (before collapsing them) -o, --output-keys KEYS Always print this comma separated keys, with their value, if they are part of an object with any diff -x, --exclude-keys KEYS Exclude these comma separated keys from comparison on both files -n, --output-new-only Output only the updated and new key/value pairs (without marking them as such).
      » npm install json-diff
    
Published   May 15, 2023
Version   1.0.6
Author   Andrey Tarantsov
🌐
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.
🌐
GitHub
github.com › benjamine › jsondiffpatch
GitHub - benjamine/jsondiffpatch: Diff & patch JavaScript objects · GitHub
(optionally) text diffing of long strings powered by google-diff-match-patch (diff at character level) reverse a delta, unpatch (eg. revert object to its original state using a delta) ... // sample data const country = { name: 'Argentina', capital: 'Buenos Aires', independence: new Date(1816, 6, 9), }; // clone country, using dateReviver for Date objects const country2 = JSON.parse(JSON.stringify(country), jsondiffpatch.dateReviver); // make some changes country2.name = 'Republica Argentina'; country2.population = 41324992; delete country2.capital; const delta = jsondiffpatch.diff(country, cou
Author   benjamine
🌐
npm
npmjs.com › package › json-diff-kit
json-diff-kit - npm
You can use your own component to visualize the diff data, or use the built-in viewer: import { Viewer } from 'json-diff-kit'; import type { DiffResult } from 'json-diff-kit'; import 'json-diff-kit/dist/viewer.css'; interface PageProps { diff: [DiffResult[], DiffResult[]]; } const Page: React.FC<PageProps> = props => { return ( <Viewer diff={props.diff} // required indent={4} // default `2` lineNumbers={true} // default `false` highlightInlineDiff={true} // default `false` inlineDiffOptions={{ mode: 'word', // default `"char"`, but `"word"` may be more useful wordSeparator: ' ', // default `""`, but `" "` is more useful for sentences }} /> ); };
      » npm install json-diff-kit
    
Published   Mar 03, 2026
Version   1.0.35
Author   Rex Zeng
🌐
npm
npmjs.com › package › json-diff-ts
json-diff-ts - npm
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: 3 days ago.
      » npm install json-diff-ts
    
Published   Mar 06, 2026
Version   4.10.0
Author   Christian Glessner
🌐
Js
json-diff-kit.js.org
JSON Diff Kit Playground
We cannot provide a description for this page right now
🌐
GitHub
github.com › lukascivil › json-difference
GitHub - lukascivil/json-difference: A simple way to find the difference between two objects or json diff · GitHub
Computes the difference between two objects and returns an intuitive result. No matter how big your JSON is, the diff will be returned pretty fast.
Author   lukascivil
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;
};
Find elsewhere
🌐
npm
npmjs.com › package › diff-json
diff-json - npm
Generates diffs of javascript objects.. Latest version: 2.0.0, last published: 7 years ago. Start using diff-json in your project by running `npm i diff-json`. There are 17 other projects in the npm registry using diff-json.
      » npm install diff-json
    
Published   May 13, 2019
Version   2.0.0
Author   viruschidai@gmail.com
Top answer
1 of 4
8

Friends! I'm really sorry if I don't understand something, or explain question in wrong terms. All I wanna do is to compare the equality of two pieces of JSON-standardized data like this:

{"skip":0, "limit":7, "arr": [1682, 439, {"x":2, arr:[]}] }

{"skip":0, "limit":7, "arr": [1682, 450, "a", ["something"] }

I'm 100% sure there will be no functions, Date, null or undefined, etc. in these data. I want to say I don't want to compare JavaScript objects in the most general case (with complex prototypes, circular links and all this stuff). The prototype of these data will be Object. I'm also sure lots of skillful programmers have answered this question before me.

The main thing I'm missing is that I don't know how to explain my question correctly. Please feel free to edit my post.

My answer:

First way: Unefficient but reliable. You can modify a generic method like this so it does not waste time looking for functions and undefined. Please note that generic method iterates the objects three times (there are three for .. in loops inside)

Second way: Efficient but has one restriction. I've found JSON.stringify is extremely fast in node.js. The fastest solution that works is:

JSON.stringify(data1) == JSON.stringify(data2)

Very important note! As far as I know, neither JavaScript nor JSON don't matter the order of the object fields. However, if you compare strings made of objects, this will matter much. In my program the object fields are always created in the same order, so the code above works. I didn't search in the V8 documentation, but I think we can rely on the fields creation order. In other case, be aware of using this method.

In my concrete case the second way is 10 times more efficient then the first way.

2 of 4
4

I've done some benchmarking of the various techniques, with underscore coming out on top:

> node nodeCompare.js 

deep comparison res: true took: 418 (underscore)
hash comparison res: true took: 933
assert compare  res: true took: 2025
string compare  res: true took: 1679

Here is the source code:

var _ = require('underscore');

var assert = require('assert');

var crypto = require('crypto');

var large = require('./large.json');

var large2 = JSON.parse(JSON.stringify(large));

var t1 = new Date();
var hash = crypto.createHash('md5').update(JSON.stringify(large)).digest('hex');
var t2 = new Date();

var res = _.isEqual(large, large2);

var t3 = new Date();

var res2 = (hash == crypto.createHash('md5').update(JSON.stringify(large2)).digest('hex'));

var t4 = new Date();

assert.deepEqual(large, large2);

var t5 = new Date();

var res4 = JSON.stringify(large) === JSON.stringify(large2);

var t6 = new Date();

console.log("deep comparison res: "+res+" took: "+ (t3.getTime() - t2.getTime()));
console.log("hash comparison res: "+res2+" took: "+ (t4.getTime() - t3.getTime()));
console.log("assert compare  res: true took: "+ (t5.getTime() - t4.getTime()));
console.log("string compare  res: "+res4+" took: "+ (t6.getTime() - t5.getTime()));
🌐
TechTutorialsX
techtutorialsx.com › 2020 › 03 › 01 › javascript-json-diff
JavaScript: JSON diff – techtutorialsx
January 25, 2025 - We will now check what is the behavior when we are diffing properties with numbers. We will do exactly the same as before but our person objects will contain a property called age. The property will contain a number. The full code can be seen below. const jsondiffpatch = require('jsondiffpatch').create(); const person = { age : 20, }; const person2 = { age : 30, }; const diff = jsondiffpatch.diff(person, person2); console.log(diff);
🌐
Benjamine
benjamine.github.io › jsondiffpatch › demo › index.html
JsonDiffPatch
JsonDiffPatch is a free online json diff tool and npm library to compare json and get a json diff.
🌐
GitHub
github.com › viruschidai › diff-json
GitHub - viruschidai/diff-json: A javascript object diff tool
var changesets = require('diff-json'); var newObj, oldObj; oldObj = { name: 'joe', age: 55, coins: [2, 5], children: [ {name: 'kid1', age: 1}, {name: 'kid2', age: 2} ]}; newObj = { name: 'smith', coins: [2, 5, 1], children: [ {name: 'kid3', age: 3}, {name: 'kid1', age: 0}, {name: 'kid2', age: 2} ]}; # Assume children is an array of child object and the child object has 'name' as its primary key diffs = changesets.diff(oldObj, newObj, {children: 'name'}); expect(diffs).to.eql([ { type: 'update', key: 'name', value: 'smith', oldValue: 'joe' }, { type: 'update', key: 'coins', embededKey: '$index'
Starred by 61 users
Forked by 15 users
Languages   CoffeeScript 99.6% | JavaScript 0.4%
🌐
npm
npmjs.com › package › json-schema-diff
json-schema-diff - npm
nodejs 10.x or higher (tested using 10.x, 12.x, 14.x and 16.x) ... This tool identifies what has changed between two json schema files. These changes are classified into two groups, added and removed.
      » npm install json-schema-diff
    
Published   Nov 21, 2025
Version   1.0.0
Author   Ben Sayers
🌐
GitHub
github.com › RexSkz › json-diff-kit
GitHub - RexSkz/json-diff-kit: A better JSON differ & viewer, support LCS diff for arrays and recognise some changes as "modification" apart from simple "remove"+"add". · GitHub
You can use your own component to visualize the diff data, or use the built-in viewer: import { Viewer } from 'json-diff-kit'; import type { DiffResult } from 'json-diff-kit'; import 'json-diff-kit/dist/viewer.css'; interface PageProps { diff: [DiffResult[], DiffResult[]]; } const Page: React.FC<PageProps> = props => { return ( <Viewer diff={props.diff} // required indent={4} // default `2` lineNumbers={true} // default `false` highlightInlineDiff={true} // default `false` inlineDiffOptions={{ mode: 'word', // default `"char"`, but `"word"` may be more useful wordSeparator: ' ', // default `""`, but `" "` is more useful for sentences }} /> ); };
Author   RexSkz
🌐
CodeProject
codeproject.com › Questions › 1164368 › How-to-detect-differences-between-two-json-string
How to detect differences between two json string in node.js
Do not try and find the page. That’s impossible. Instead only try to realise the truth - For those who code; Updated: 1 Jul 2007
🌐
Npm
npm.io › package › json-diff
Json-diff NPM | npm.io
% json-diff --help Usage: json-diff [-vCjfonskKp] first.json second.json Arguments: <first.json> Old file <second.json> New file General options: -v, --verbose Output progress info -C, --[no-]color Colored output -j, --raw-json Display raw JSON encoding of the diff -f, --full Include the equal sections of the document, not just the deltas --max-elisions COUNT Max number of ...s to show in a row in "deltas" mode (before collapsing them) -o, --output-keys KEYS Always print this comma separated keys, with their value, if they are part of an object with any diff -x, --exclude-keys KEYS Exclude these comma separated keys from comparison on both files -n, --output-new-only Output only the updated and new key/value pairs (without marking them as such).