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

后端 未结 10 1128
春和景丽
春和景丽 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:17

    If you wanna compare only objects:

    b = {"1":{"prod":"fibaro"},"2":{"prod":"aeotec"},"3":{"prod":"sw"}}; 
    a = {"1":{"prod":"fibaro"}};
    
    
    _.intersectObjects = function(a,b){
        var m = Object.keys(a).length;
        var n = Object.keys(b).length;
        var output;
        if (m > n) output = _.clone(a); else output = _.clone(b);
    
        var keys = _.xor(_.keys(a),_.keys(b));
        for(k in keys){
            console.log(k);
            delete output[keys[k]];
        }
        return output;
    }
    _.intersectObjects(a,b); // this returns { '1': { prod: 'fibaro' } }
    
    0 讨论(0)
  • 2020-12-02 16:20

    In lodash 4.0.0. We can try like this

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

    Output:

    [ {'id': 1, 'name': 'jake' } ];

    0 讨论(0)
  • 2020-12-02 16:21

    Technically, it does work on objects, but you need to be careful of reference equality.

    var jake = {'id': 1, 'name': 'jake' },
        jenny = {'id':4, 'name': 'jenny'},
        nick =  {'id': 9, 'name': 'nick'};
    var a = [jake, jenny]
    var b = [jake, nick];
    
    _.intersection(a, b);
    // is
    [jake]
    
    0 讨论(0)
  • 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.

    <script type="text/javascript">
    jQuery(document).ready(function(){
        var a = [ {'id': 1, 'name': 'jake' }, {'id':4, 'name': 'jenny'} ];
        var b = [ {'id': 1, 'name': 'jake' }, {'id': 9, 'name': 'nick'} ];
        var c=[];
        jQuery.each(a, function(ka,va) {
           jQuery.each(b, function(kb,vb) {      
                    if(compare(va,vb))
                        c.push(va); 
         });   
        });
         console.log(c);  
    });
    function compare(a,b){
      if(a.id==b.id&&a.name==b.name)
         return true;
      else return false;
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题