How to use underscore's “intersection” on objects?

后端 未结 10 1155
春和景丽
春和景丽 2020-12-02 15:49
_.intersection([], [])

only works with primitive types, right?

It doesn\'t work with objects. How can I make it work with objects (maybe b

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 16:22

    var a = [ {'id': 1, 'name': 'jake' }, {'id':4, 'name': 'jenny'} ];
    var b = [ {'id': 1, 'name': 'jake' }, {'id': 9, 'name': 'nick'} ];
    

    Working function:

     function intersection(a,b){
      var c=[];
       for(m in a){
          for(n in b){
             if((a[m].id==a[n].id)&&(a[m].name==b[n].name))
                     c.push(a[m]);          
          }}
        return c;
      }
    console.log(intersection(a,b));
    

    I have also tried code in jQuery specially after Pointy's suggestion. Compare has to be customizable as per the structure of JSON object.

    
    

提交回复
热议问题