Search code examples
javascriptlodash

Javascript compare objects having functions using lodash isEqual


how to compare two objects for equality if they have functions? lodash's isEqual works really well until functions are thrown in:

_.isEqual({
    a: 1,
    b: 2
}, {
    b: 2,    
    a: 1
});

// -> true

_.isEqual({
    a: 1,
    b: 2,
    c: function () {
        return 1;
    }
}, {
    a: 1,    
    b: 2,
    c: function () {
          return 1;
    }
});

// -> false

Solution

  • Are you sure you want to compare functions? If you only care about comparing every property that isn't a function, this is easy to do with lodash:

    var o1 = { a: 1, b: 2, c: function() { return 1; } },
        o2 = { a: 1, b: 2, c: function() { return 1; } };
    
    _.isEqual(o1, o2)
    // → false
    
    _.isEqual(_.omit(o1, _.functions(o1)), _.omit(o2, _.functions(o2)));
    // → true
    

    The functions() function returns a list of function properties, and using omit(), you can get rid of them.