2017-07-26 100 views
1

我有兩個數組,餘額和承諾underscorejs如何比較兩個數組?

balances = [ 
{name: 'vacation', value: ''21}, 
{name: 'account', value: '200'}, 
{name: 'order', value: '15'}, 
] 

commits = [ 
{balanceName: 'vacation', paramName: 'number of days'}, 
{balanceName: 'order', paramName: 'number of items'} 
] 

我想刪除表格餘額究竟是不是在犯,在這個例子中,我想刪除餘額賬戶價值的原因是沒有在任何的balanceName的提交 如何通過下劃線或任何其他庫執行此操作

+0

您可以參考此鏈接https://stackoverflow.com/questions/10110510/underscore-js-determine-if-all-values-in-an-array-of-arrays-match –

+0

可能的重複[如何過濾數組時,對象的鍵值是在數組中](https://stackoverflow.com/questions/35817565/how-to-filter-array-when-object-key-value-is-in-array) –

回答

2

你可以做,使用undescore.js這樣的:

var balances = [ 
 
{name: 'vacation', value: '21'}, 
 
{name: 'account', value: '200'}, 
 
{name: 'order', value: '15'} 
 
] 
 

 
var commits = [ 
 
{balanceName: 'vacation', paramName: 'number of days'}, 
 
{balanceName: 'order', paramName: 'number of items'} 
 
] 
 
balances2= 
 
_.filter(balances,(b)=>commits.map(c=>c.balanceName).indexOf(b.name)>-1); 
 

 
console.log("using shorter syntax"); 
 
console.log(balances) 
 

 
//OR 
 
balances= 
 
    _.filter(balances,function(b){return commits.map(function(c){return c.balanceName}).indexOf(b.name)>-1}); 
 
    
 
    console.log("ES5 syntax"); 
 
console.log(balances2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

_.filter將返回符合條件的所有條目。例如_.find只會返回第一個條目。 我也使用_.map它使用轉換函數(在我的案例c=>c.balanceName)將具有多個屬性的數組轉換爲其他數組。

+0

它的工作原理,謝謝您 – scully

-1

不需要此庫的庫。

function contains(commits, name) 
{ 
    commits.some(function(x) { return x.balanceName === name}); 
} 

for(blance in balances) { 
    if (contains(commits, balance.name){ 
     // Remove balance 
    } 
}