2017-04-06 109 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);