jsondiffpatch icon indicating copy to clipboard operation
jsondiffpatch copied to clipboard

Ignore transient fields

Open apalskoi opened this issue 13 years ago • 8 comments

Is there an easy way to configure JsonDiffPatch to ignore some of the fields when comparing two objects? I have a scenario where JSON data is loaded from a storage and then additional derived fields are added to it for internal use by the application. When running diff, I don't want them to be included in the patch.

apalskoi avatar Jan 31 '13 18:01 apalskoi

No, unfortunately, there's no way to filter fields, I take it as a feature request. I think having the opt to provide a filter: function(original, new, memberName) { return true/false; } would be the way. ps: pull requests are welcome.

benjamine avatar Jan 31 '13 19:01 benjamine

+1 for this feature. Specifically, I am in a situation where I want to ignore some fields tacked on by the framework I am using (angularjs ng-repeat directive).

sansjunk avatar Mar 02 '15 09:03 sansjunk

@sansjunk I just create temporary objects for diffing and delete them from both the objects. just before the diff is done. ''' delete left._ignoreField; delete right._ignoreField; '''

enkodellc avatar Mar 02 '15 09:03 enkodellc

Yes that's one solution, but in my case I need to retain the added fields since they are used by the framework to track changes. Anyway I am working around this issue but I think this would be a good feature to have.

sansjunk avatar Mar 02 '15 10:03 sansjunk

I'm adding the example I used in #77 just for clarity here too:

this is an example of how to filter object properties by writing a diff plugin:

var diffpatcher = jsondiffpatch.create();

// insert a new diff filter, right before "objects" one
diffpatcher.processor.pipes.diff.before('objects', objectPropertyTrimFilter);

function trimObject(obj) {
  trimmedObject = {};
  for (var name in obj) {
    if (name.slice(0, 2) !== '$$') {
      trimmedObject[name] = obj[name];
    }
  }
  return trimmedObject;
}

function objectPropertyTrimFilter(context) {
  if (!context.leftIsArray && context.leftType === 'object') {
    // replace context left object with trimmed version
    context.left = trimObject(context.left);
  }
  if (!context.rightIsArray && context.rightType === 'object') {
    // replace context right object with trimmed version
    context.right = trimObject(context.right);
  }
}


// use your diffpatcher
left = { a: 1, $$key: 4 };
right = { a: 3, $$key: 6 };
diffpatcher.diff(left, right); 
// result is { a: [1, 3] }

benjamine avatar Jun 16 '15 21:06 benjamine

+1

m-a-r-c-e-l-i-n-o avatar Jul 18 '15 19:07 m-a-r-c-e-l-i-n-o

+1

co-dh avatar Nov 25 '15 22:11 co-dh

done, I added support for a propertyFilter(name, context) option, that would let you ignore properties either by name, or by any other test of the context left or right objects (see https://github.com/benjamine/jsondiffpatch#options )

benjamine avatar Feb 14 '16 04:02 benjamine