0_0
0_0

Reputation: 537

Find difference in Objects using underscore.js

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.

Upvotes: 1

Views: 4792

Answers (3)

Thierry D.
Thierry D.

Reputation: 388

/**
 * 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);
}

Upvotes: 5

Aren Hovsepyan
Aren Hovsepyan

Reputation: 2047

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>

Upvotes: 0

Caius
Caius

Reputation: 243

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

Upvotes: 1

Related Questions