使用underscore.js找出对象的差异

时间:2016-07-29 18:51:19

标签: javascript jquery underscore.js

所以我有两个JSON对象,我试图使用下划线js找到它们之间的差异。但是出于某种原因,它将整个对象归还给我,而不仅仅是返回差异。我的目标是让模式成为唯一不同的东西。

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));

我是否正确理解_.difference的用例?如果需要,可以使用JSFiddle

3 个答案:

答案 0 :(得分:2)

{{1}}

答案 1 :(得分:1)

_。差异是为了比较数组,你要比较对象。请参阅此答案:using underscore's “difference” method on arrays of objects

答案 2 :(得分:0)

下划线有方法isMatch,但没有方法会返回对象的差异,它将2作为参数Objects并匹配其属性

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

您可以创建自己的实现



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>
&#13;
&#13;
&#13;