How can I get a list of the differences between two JavaScript object graphs?

前端 未结 10 565
终归单人心
终归单人心 2020-11-29 01:02

I want to be able to get a list of all differences between two JavaScript object graphs, with the property names and values where the deltas occur.

For what it is w

10条回答
  •  暖寄归人
    2020-11-29 01:17

    I recently wrote a module to do this, because I wasn't satisfied with the numerous diffing modules I found (I listed a bunch of the most popular modules and why they weren't acceptable in the readme of my module). Its called odiff: https://github.com/Tixit/odiff . Here's an example:

    var a = [{a:1,b:2,c:3},              {x:1,y: 2, z:3},              {w:9,q:8,r:7}]
    var b = [{a:1,b:2,c:3},{t:4,y:5,u:6},{x:1,y:'3',z:3},{t:9,y:9,u:9},{w:9,q:8,r:7}]
    
    var diffs = odiff(a,b)
    
    /* diffs now contains:
    [{type: 'add', path:[], index: 2, vals: [{t:9,y:9,u:9}]},
     {type: 'set', path:[1,'y'], val: '3'},
     {type: 'add', path:[], index: 1, vals: [{t:4,y:5,u:6}]}
    ]
    */
    

提交回复
热议问题