Search code examples
jsonangularjson-patch

How to use fast-json-patch in Angular 2 applications?


I want to use the "fast-json-patch" library (https://github.com/Starcounter-Jack/JSON-Patch) in an Angular 2 application.

I have tried adding:

'fast-json-patch': 'vendor/fast-json-patch/dist/json-patch-duplex.min.js'

in the system-config.ts file under the map but it doesn't work when importing fast-json-patch


Solution

  • 1) Install the package

    npm install fast-json-patch --save
    

    2) In the component, where you want to use ist, import the functions you need:

    import { compare } from 'fast-json-patch';
    

    3) To create a Patch compare the old object with the new object:

    const patch = compare(oldObj, modifiedObj);
    

    4) Print out the result:

    console.log(patch);
    
    0:{op: "replace", path: "/firmendetails/registergericht", value: "Darmstadt xx"}
    1:{op: "remove", path: "/firmendetails/handelsname"}
    2:{op: "remove", path: "/firmendetails/firma"}
    3:{op: "remove", path: "/firmendetails/rechtsform"}