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

前端 未结 10 582
终归单人心
终归单人心 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:32

    You can also try rus-diff https://github.com/mirek/node-rus-diff which generates MongoDB compatible (rename/unset/set) diff.

    For your example objects:

    var person1 = {
      FirstName: "John",
      LastName: "Doh",
      Age: 30,
      EMailAddresses: ["john.doe@gmail.com", "jd@initials.com"],
      Children: [
        {
          FirstName: "Sara",
          LastName: "Doe",
          Age: 2
        }, {
          FirstName: "Beth",
          LastName: "Doe",
          Age: 5
        }
      ]
    };
    
    var person2 = {
      FirstName: "John",
      LastName: "Doe",
      Age: 33,
      EMailAddresses: ["john.doe@gmail.com", "jdoe@hotmail.com"],
      Children: [
        {
          FirstName: "Sara",
          LastName: "Doe",
          Age: 3
        }, {
          FirstName: "Bethany",
          LastName: "Doe",
          Age: 5
        }
      ]
    };
    
    var rusDiff = require('rus-diff').rusDiff
    
    console.log(rusDiff(person1, person2))
    

    It generates a list of sets:

    { '$set': 
       { 'Age': 33,
         'Children.0.Age': 3,
         'Children.1.FirstName': 'Bethany',
         'EMailAddresses.1': 'jdoe@hotmail.com',
         'LastName': 'Doe' } }
    

提交回复
热议问题