1

So I have two JSON objects and I am trying to find difference between them using underscore js. However for some reason its returning me the whole object instead of just returning the difference. My goal here is to get the pattern back as its the only thing different.

var a = {
        "name":"donor",
        "label":"Donor Data File (donor)",
        "pattern":"^donor(\\.[a-zA-Z0-9]+)?\\.txt(?:\\.gz|\\.bz2)?$"
};
var b = {
         "name":"donor",
         "label":"Donor Data File (donor)",
         "pattern":"^donor(\\.[a-zA-Z0-9]+)?\\.txt(?:\\.gz)?$"
};

console.log(_.difference(a,b));

Am I not understanding the use case of _.difference properly? Heres a JSFiddle in case needed.

0_0
  • 537
  • 1
  • 7
  • 20

3 Answers3

5
/**
 * Deep diff between two object, using underscore
 * @param  {Object} object Object compared
 * @param  {Object} base   Object to compare with
 * @return {Object}        Return a new object who represent the diff
 */
const difference = (object, base) => {
  const changes = (object, base) => (
    _.pick(
      _.mapObject(object, (value, key) => (
        (!_.isEqual(value, base[key])) ?
          ((_.isObject(value) && _.isObject(base[key])) ? changes(value, base[key]) : value) :
          null
      )),
      (value) => (value !== null)
    )
  );
  return changes(object, base);
}
Thierry D.
  • 338
  • 3
  • 11
1

_.difference is meant to compare arrays, you're comparing objects. See this answer: using underscore's “difference” method on arrays of objects

Community
  • 1
  • 1
Caius
  • 243
  • 1
  • 5
0

Underscore has method isMatch,but no method that will return difference for objects, that takes 2 as parameter Objects and match their properties

var stooge = {name: 'moe', age: 32};
_.isMatch(stooge, {age: 32});

you can create your own implementation

function getDiffProperties(object1,object2){
      var difference  = [];
  
      for(key in object1){
        if(object1[key] != object2[key]){
          difference.push(key)
        }
      }

      for(key in object2){
        if(object1[key] != object2[key]){
          difference.push(key)
        }
      }
     
     return difference
}

console.log(getDiffProperties({name: 'moe', age: 32},{age: 32}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Aren Hovsepyan
  • 1,947
  • 2
  • 17
  • 45
  • Match returns a boolean, though. OP is trying to get an object back that has the same shape as only the differing fields. – Dave Newton Jul 29 '16 at 18:56