benjamine / jsondiffpatch

Diff & patch JavaScript objects
MIT License
4.77k stars 464 forks source link

jsonpatch formatter generate bad patches #326

Open keelii opened 1 year ago

keelii commented 1 year ago
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/jsondiffpatch/dist/jsondiffpatch.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/fast-json-patch@3.1.1/dist/fast-json-patch.min.js"></script>
</head>
<body>

<script>
    var differ = new jsondiffpatch.DiffPatcher({
        objectHash(o, i) {
            return o.id || '$$index:' + i
        },
    })

    var d1 = {
        children: [
            {
                id: 1,
                children: [
                    { id: 2, key: 1 }
                ]
            }
        ]
    }
    var d2 = {
        children: [
            { id: 2, key: 1 },
            {
                id: 1,
                children: []
            }
        ]
    }

    var delta = differ.diff(d1, d2)

    var jsonPatches = jsondiffpatch.formatters.jsonpatch.format(delta)
    /*                                   ↓ only one child
    [{"op": "remove", "path": "/children/1/children/0"},
    {"op": "add", "path": "/children/0", "value": {"id": 2, "key": 1 } } ]
    */

    jsonpatch.applyPatch(d1, jsonPatches)  
    // fast-json-patch.min.js:8 Uncaught TypeError: Cannot read properties of undefined (reading 'children')

</script>

</body>
</html>