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
🌐
GitHub
github.com › ltwlf › json-diff-ts
GitHub - ltwlf/json-diff-ts: A diff tool for JavaScript written in TypeScript. · GitHub
Modern TypeScript JSON diff library - json-diff-ts is a lightweight, high-performance TypeScript library for calculating and applying differences between JSON objects.
Author   ltwlf
🌐
npm
npmjs.com › package › json-diff-ts
json-diff-ts - npm
Modern TypeScript JSON diff library - json-diff-ts is a lightweight, high-performance TypeScript library for calculating and applying differences between JSON objects.
      » npm install json-diff-ts
    
Published   Feb 15, 2026
Version   4.9.1
Author   Christian Glessner
🌐
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.
🌐
CodeSandbox
codesandbox.io › s › json-diff-ts-2tx774
json-diff-ts - CodeSandbox
August 31, 2023 - 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.
Published   Aug 31, 2023
🌐
npm
npmjs.com › package › json-diff-kit
json-diff-kit - npm
A better JSON differ & viewer library written in TypeScript.
      » npm install json-diff-kit
    
Published   Mar 03, 2026
Version   1.0.35
Author   Rex Zeng
🌐
CodeSandbox
codesandbox.io › examples › package › json-diff-ts
json-diff-ts examples - CodeSandbox
AboutModern TypeScript JSON diff library - Zero dependencies, high performance, ESM + CommonJS support.
🌐
npm
npmjs.com › package › @types › json-diff
@types/json-diff - npm
TypeScript definitions for json-diff. Latest version: 1.0.3, last published: 2 years ago. Start using @types/json-diff in your project by running `npm i @types/json-diff`. There are 14 other projects in the npm registry using @types/json-diff.
      » npm install @types/json-diff
    
🌐
GitHub
github.com › thiagomayrink › json-diff-ts-cjs
GitHub - thiagomayrink/json-diff-ts-cjs: A JSON diff tool for JavaScript written in TypeScript. forked from: https://github.com/ltwlf/json-diff-ts.git
A JSON diff tool for JavaScript written in TypeScript. forked from: https://github.com/ltwlf/json-diff-ts.git - thiagomayrink/json-diff-ts-cjs
Author   thiagomayrink
Find elsewhere
🌐
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
🌐
Js
json-diff-kit.js.org
JSON Diff Kit Playground
We cannot provide a description for this page right now
🌐
Reddit
reddit.com › r/reactjs › weekend project: json diff tool built with react + typescript + vite
r/reactjs on Reddit: Weekend project: JSON Diff Tool built with React + TypeScript + Vite
October 19, 2025 -

Built a JSON/YAML comparison tool this weekend as a React learning project.

Tech choices:

  • React 18 with hooks (useState, useEffect)

  • TypeScript for type safety

  • Vite for blazing fast dev experience

  • Tailwind CSS for styling

  • Deployed on Vercel (auto-deployment from GitHub)

What it does: Compare configuration files side-by-side with color-coded differences.

Try it: https://diff-master.vercel.app/

React patterns used:

  • Component composition (ComparisonArea, ResultsSection, Header)

  • Custom hooks for state management

  • TypeScript interfaces for type safety

  • Responsive design with Tailwind

Interesting challenges solved:

  • Deep object comparison algorithm

  • Real-time format detection (JSON vs YAML)

  • Efficient diff calculation for large files

  • Markdown export functionality

Built with bolt.diy (AI-assisted coding) which helped me:

  • Scaffold the project structure quickly

  • Generate TypeScript types

  • Debug TypeScript compilation errors

  • Deploy to Vercel

What would you improve from a React architecture perspective?

https://imgur.com/a/Ye6WFDQ

🌐
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
🌐
GitHub
github.com › bustle › yajsondiff
GitHub - bustle/yajsondiff: Yet another JSON diff utility, for generating and applying patches
yajsondiff is Yet Another Json Diffing library. It is a Typescript fork of Deep Diff.
Author   bustle
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;
};
🌐
Cloudsmith
cloudsmith.com › navigator › npm › @types › json-diff
@types/json-diff (1.0.3) - npm Package Quality | Cloudsmith Navigator
$npm install @types/json-diff · /Processing... ✓Done · Start your free trial · 1.0.3 · Stable version · 2years ago · Released · Loading Version Data · NPM on Cloudsmith · Learn more about NPM on Cloudsmith ·
🌐
npm
npmjs.com › package › json-diff
json-diff - npm
-s, --sort Sort primitive values in arrays before comparing -k, --keys-only Compare only the keys, ignore the differences in values -K, --keep-unchanged-values Instead of omitting values that are equal, output them as they are -p, --precision DECIMALS Round all floating point numbers to this number of decimal places prior to comparison -h, --help Display this usage information ... var jsonDiff = require('json-diff'); console.log(jsonDiff.diffString({ foo: 'bar' }, { foo: 'baz' })); // Output: // { // - foo: "bar" // + foo: "baz" // } // As above, but without console colors console.log(jsonDiff
      » npm install json-diff
    
Published   May 15, 2023
Version   1.0.6
Author   Andrey Tarantsov
🌐
GitHub
github.com › topics › json-diff
json-diff · GitHub Topics · GitHub
All 34 JavaScript 13 TypeScript 5 Go 4 C# 2 C++ 2 Java 2 Python 2 CoffeeScript 1 Dart 1 HTML 1 · Star 8 · Configable json diff viewer in browser · react minimalist json-diff jsondiff jsondiffrender json-diff-viewer · Updated · Apr 9, 2024 · TypeScript ·
🌐
Playcode
playcode.io › json-diff
JSON Diff Online - Free JSON Compare & Merge Tool
[ { "op": "replace", "path": "/version", "value": "2.1" }, { "op": "add", "path": "/features/-", "value": "JSON Diff" } ] ... JavaScript PlaygroundJavaScript CompilerTypeScript PlaygroundPython CompilerPython PlaygroundC++ CompilerC++ PlaygroundC CompilerGo CompilerSQL CompilerSQL EditorSQL OnlineSQL PlaygroundHTML EditorCSS Playground · ReactVueAngularSvelteSolidFramer MotionThree.jsPIXI.jsp5.jsCanvas · JSON FormatterJSON to TypeScriptRegex TesterHTML RunnerLodashRxJsRimbujQuery