2017-04-06 106 views
1

我有两个对象数组,我需要根据属性进行过滤。在香草中比较两个包含对象的数组JS

var port = [ 
     { 
     name: 'Cali', 
     type:'Mine', 
     location = { 
      lat: '89.9939', 
      lon: '-79.9999' 
     } 
     }, 
     { 
     name: 'Denver', 
     type:'Port', 
     location = { 
      lat: '67.9939', 
      lon: '-85.9999' 
     } 
     }, 
     { 
     name: 'Seattle', 
     type:'Port', 
     location = { 
      lat: '167.9939', 
      lon: '-85.9999' 
     } 
     }, 
     ........... 
    ] 

而且有另一个对象

var child = [ 
    { 
     lat: '89.9939', 
     lon: '-79.9999' 
    }, 

    { 
     lat: '67.9939', 
     lon: '-85.9999' 
    } 
    ] 

我使用的过滤器

var result = port.filter(function(el){ 
        return el.location.lat === child.lat 
       }); 

我怎么可以循环用于我的第二个阵列。我的数据在这种情况下相当大。

+0

您可以在过滤功能使用child.find()。 –

回答

1

您可以使用Array#some来确定child阵列中的任何对象是否与port阵列中的任何对象具有相同的lat值。

var port = [{name:'Cali',type:'Mine',location:{lat:'89.9939',lon:'-79.9999'}},{name:'Denver',type:'Port',location:{lat:'67.9939',lon:'-85.9999'}},{name:'Seattle',type:'Port',location:{lat:'167.9939',lon:'-85.9999'}}], 
 
    child = [{lat:'89.9939',lon:'-79.9999'},{lat:'67.9939',lon:'-85.9999'}], 
 
    result = port.filter(el => child.some(v => v.lat == el.location.lat)); 
 

 
    console.log(result);