19

デルタが発生するプロパティ名と値を使用して、2 つの JavaScript オブジェクト グラフ間のすべての違いのリストを取得できるようにしたいと考えています。

価値のあることとして、これらのオブジェクトは通常、サーバーから JSON として取得され、通常は数層の深さしかありません (つまり、それ自体がデータを持つオブジェクトの配列であり、他のデータ オブジェクトを持つ配列である可能性があります)。

基本的なプロパティの変更だけでなく、配列のメンバー数の違いなども見たいです。

答えが得られない場合は、おそらく自分でこれを書くことになりますが、誰かがすでにこの作業を行っているか、行っている人を知っていることを願っています.


編集: これらのオブジェクトは通常、互いに構造が非常に似ているため、互いにまったく異なるオブジェクトについて話しているわけではありませんが、3 つまたは 4 つのデルタを持つ可能性があります。

4

10 に答える 10

21

これが私の問題に対する部分的で素朴な解決策です - 私はそれをさらに開発するにつれてこれを更新します.

function findDifferences(objectA, objectB) {
   var propertyChanges = [];
   var objectGraphPath = ["this"];
   (function(a, b) {
      if(a.constructor == Array) {
         // BIG assumptions here: That both arrays are same length, that
         // the members of those arrays are _essentially_ the same, and 
         // that those array members are in the same order...
         for(var i = 0; i < a.length; i++) {
            objectGraphPath.push("[" + i.toString() + "]");
            arguments.callee(a[i], b[i]);
            objectGraphPath.pop();
         }
      } else if(a.constructor == Object || (a.constructor != Number && 
                a.constructor != String && a.constructor != Date && 
                a.constructor != RegExp && a.constructor != Function &&
                a.constructor != Boolean)) {
         // we can safely assume that the objects have the 
         // same property lists, else why compare them?
         for(var property in a) {
            objectGraphPath.push(("." + property));
            if(a[property].constructor != Function) {
               arguments.callee(a[property], b[property]);
            }
            objectGraphPath.pop();
         }
      } else if(a.constructor != Function) { // filter out functions
         if(a != b) {
            propertyChanges.push({ "Property": objectGraphPath.join(""), "ObjectA": a, "ObjectB": b });
         }
      }
   })(objectA, objectB);
   return propertyChanges;
}

そして、これがどのように使用されるか、そしてそれが提供するデータのサンプルです(長い例を許してください、しかし私は比較的重要なものを使いたいです):

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 differences = findDifferences(person1, person2);

この時点で、differencesJSON にシリアル化した場合の配列は次のようになります。

[
   {
      "Property":"this.LastName", 
      "ObjectA":"Doh", 
      "ObjectB":"Doe"
   }, {
      "Property":"this.Age", 
      "ObjectA":30, 
      "ObjectB":33
   }, {
      "Property":"this.EMailAddresses[1]", 
      "ObjectA":"jd@initials.com", 
      "ObjectB":"jdoe@hotmail.com"
   }, {
      "Property":"this.Children[0].Age", 
      "ObjectA":2, 
      "ObjectB":3
   }, {
      "Property":"this.Children[1].FirstName", 
      "ObjectA":"Beth", 
      "ObjectB":"Bethany"
   }
]

値のはthisProperty比較されたオブジェクトのルートを参照します。したがって、このソリューションはまだが必要としているものではありませんが、かなり近いものです。

これが誰かに役立つことを願っています。改善のための提案があれば、私は耳を傾けます。私はこれを昨夜遅く(つまり今朝早く)書いたので、完全に見落としている部分があるかもしれません。

ありがとう。

于 2008-11-05T19:36:46.477 に答える
8

それを可能にするobjectDiff ライブラリがあります。そのデモ ページで、2 つの JavaScript オブジェクトの違いを確認できます。

于 2011-07-08T10:08:28.977 に答える
7

また、MongoDB と互換性のある (rename/unset/set) diff を生成するrus-diff https://github.com/mirek/node-rus-diffを試すこともできます。

サンプル オブジェクトの場合:

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))

セットのリストを生成します。

{ '$set': 
   { 'Age': 33,
     'Children.0.Age': 3,
     'Children.1.FirstName': 'Bethany',
     'EMailAddresses.1': 'jdoe@hotmail.com',
     'LastName': 'Doe' } }
于 2014-03-11T20:07:11.670 に答える
5

解決策 1

JSON.stringify(obj) を使用して、比較するオブジェクトの文字列表現を取得します。文字列をファイルに保存します。テキスト ファイルを比較するには、任意の差分ビューアーを使用します。

注: JSON.stringify は、関数定義を指すプロパティを無視します。

解決策 2

これは、関数 _.isEqual ( http://documentcloud.github.com/underscore/ ) の修正版です。変更の提案はお気軽にどうぞ!2 つのオブジェクトの最初の違いがどこで発生するかを把握するために書きました。

// Given two objects find the first key or value not matching, algorithm is a
// inspired by of _.isEqual.
function diffObjects(a, b) {
  console.info("---> diffObjects", {"a": a, "b": b});
  // Check object identity.
  if (a === b) return true;
  // Different types?
  var atype = typeof(a), btype = typeof(b);
  if (atype != btype) {
    console.info("Type mismatch:", {"a": a, "b": b});
    return false;
  };
  // Basic equality test (watch out for coercions).
  if (a == b) return true;
  // One is falsy and the other truthy.
  if ((!a && b) || (a && !b)) {
    console.info("One is falsy and the other truthy:", {"a": a, "b": b});
    return false;
  }
  // Unwrap any wrapped objects.
  if (a._chain) a = a._wrapped;
  if (b._chain) b = b._wrapped;
  // One of them implements an isEqual()?
  if (a.isEqual) return a.isEqual(b);
  // Check dates' integer values.
  if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
  // Both are NaN?
  if (_.isNaN(a) && _.isNaN(b)) {
    console.info("Both are NaN?:", {"a": a, "b": b});
    return false;
  }
  // Compare regular expressions.
  if (_.isRegExp(a) && _.isRegExp(b))
    return a.source     === b.source &&
           a.global     === b.global &&
           a.ignoreCase === b.ignoreCase &&
           a.multiline  === b.multiline;
  // If a is not an object by this point, we can't handle it.
  if (atype !== 'object') {
    console.info("a is not an object:", {"a": a});
    return false;
  }
  // Check for different array lengths before comparing contents.
  if (a.length && (a.length !== b.length)) {
    console.info("Arrays are of different length:", {"a": a, "b": b});
    return false;
  }
  // Nothing else worked, deep compare the contents.
  var aKeys = _.keys(a), bKeys = _.keys(b);
  // Different object sizes?
  if (aKeys.length != bKeys.length) {
    console.info("Different object sizes:", {"a": a, "b": b});
    return false;
  }
  // Recursive comparison of contents.
  for (var key in a) if (!(key in b) || !diffObjects(a[key], b[key])) return false;
  return true;
};
于 2011-07-08T10:03:20.390 に答える
3

NodeJS を使用している場合、このスクリプトには NPM バージョンもあります。https://github.com/NV/objectDiff.js

喜ぶ。

于 2013-03-24T11:01:34.570 に答える
1

私が見つけたライブラリはどれも十分ではなかったので、独自の AngularJS ファクトリを作成しました。両方の方法でオブジェクトを比較し、同じ構造内の違いのみを返します。

/**
 * Diff
 * Original author: Danny Coulombe
 * Creation date: 2016-05-18
 * 
 * Work with objects to find their differences.
 */
controllers.factory('diff', [function() {

    var factory = {

        /**
         * Compare the original object with the modified one and return their differences.
         * 
         * @param original: Object
         * @param modified: Object
         * 
         * @return Object
         */
        getDifferences: function(original, modified) {

            var type = modified.constructor === Array ? [] : {};
            var result = angular.copy(type);
            var comparisons = [[original, modified, 1], [modified, original, 0]];

            comparisons.forEach(function(comparison) {

                angular.forEach(comparison[0], function(value, key) {

                    if(result[key] === undefined) {

                        if(comparison[1][key] !== undefined && value !==    null && comparison[1][key] !== null && [Object, Array].indexOf(comparison[1][key].constructor) !== -1) {

                            result[key] = factory.getDifferences(value, comparison[1][key]);
                        }
                        else if(comparison[1][key] !== value) {

                            result[key] = comparison[comparison[2]][key];
                        }

                        if(angular.equals(type, result[key])
                        || result[key] === undefined
                        || (
                            comparison[0][key] !== undefined
                            && result[key] !== null
                            && comparison[0][key] !== null
                            && comparison[0][key].length === comparison[1][key].length
                            && result[key].length === 0
                        )) {
                            delete result[key];
                        }
                    }
                });
            });

            return result;
        }
    };

    return factory;
}]);
于 2016-05-18T19:18:40.943 に答える
1

最近、これを行うためのモジュールを作成しました。これは、見つけた多数の差分モジュールに満足できなかったためです (最も人気のあるモジュールの束と、モジュールの readme でそれらが受け入れられない理由をリストしました)。その名前はodiff: https://github.com/Tixit/odiffです。次に例を示します。

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}]}
]
*/
于 2015-07-06T20:27:10.083 に答える