Using underscore.js to compare two Objects

后端 未结 3 1735
醉梦人生
醉梦人生 2020-12-16 11:53

I\'m trying to compare two objects with underscore.

Object 1 (Filter)

{
  \"tuxedoorsuit\":\"tuxedoorsuit-tuxedo\",
  \"occasions\":         


        
相关标签:
3条回答
  • 2020-12-16 12:07

    To Compare two objects using underscore.js

     **isEqual :** _.isEqual(object, other) 
    

    Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.

    Ex :

    var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};
        var clone  = {name: 'moe', luckyNumbers: [13, 27, 34]};
         _.isEqual(stooge, clone)  
          Returns True
    
    0 讨论(0)
  • 2020-12-16 12:28

    Based on previous function created simple consoling out function:

    var compareMe = function (obj1, obj2, parentKey) {
      parentKey = parentKey || '';
      _.each(_.keys(obj1), function (key) {
        if(_.isObject(obj1[key]) ) {
            compareMe(obj1[key], obj2[key], parentKey + key + '.')
        } else {
            if (!_.has(obj2, key) || !_.isEqual(obj1[key], obj2[key])) {
                console.log(parentKey + key, obj1[key], obj2[key]);
            }
        }
      })
    };
    

    And call like: compareMe(obj1, obj1)

    0 讨论(0)
  • 2020-12-16 12:30

    Edit: As per Arnaldo's comment, you can use isMatch function, like this

    console.log(_.isMatch(object2, object1));
    

    The description says,

    _.isMatch(object, properties)

    Tells you if the keys and values in properties are contained in object.

    If you want to iterate yourself, just use _.keys and _.every, like this

    _.every(_.keys(object1), function(currentKey) {
        return _.has(object2, currentKey) &&
                        _.isEqual(object1[currentKey], object2[currentKey]);
    });
    

    Or the chained version,

    var result = _.chain(object1)
        .keys()
        .every(function(currentKey) {
            return _.has(object2, currentKey) &&
                _.isEqual(object1[currentKey], object2[currentKey]);
        })
        .value();
    

    If the result is true, it means that all the keys in object1 are in object2 and their values are also equal.

    This basically iterates through all the keys of object1 and checks if the value corresponding to the key in object1 is equal to the value in object2.

    0 讨论(0)
提交回复
热议问题