2017-09-21 95 views
0

我從API獲取數據。如何從React中的另一個陣列的所有元素過濾數組

data1 = [ 
    {id:1, name:'Ant'}, 
    {id:2, name:'Bird'}, 
    {id:4, name:'Dog'}, 
    {id:5, name:'Egg'} 
]; 

data2 = [ 
    {id:2, name:'Bird'}, 
    {id:3, name:'Cat'}, 
    {id:4, name:'Dog'}, 
    {id:6, name:'Fish'} 
]; 

,我編碼使用過濾器和地圖陣列來獲得2個陣列的數據,但我不知道如何過濾「數據2」中的「數據1」得到的結果(查身份證,如果是同樣不會在結果中顯示)

我希望結果是

result = [ 
    {id:1, name:'Ant'}, 
    {id:3, name:'Cat'}, 
    {id:5, name:'Egg'}, 
    {id:6, name:'Fish'} 
]; 

這是我的代碼。

let getExistdata = {...this.props.data1.data} 

let getExistedDataId = this.props.animal.data.map((existData)=> { 
    let animalList= this.props.data2.data.filter(animal=> (animal.id !== this.props.id) && (animal.id !== existData.id)); 
    console.log(animalList); 

    return animalList; 

}); 

謝謝

+0

什麼是過濾的條件。你需要提及併發布一些你試過的代碼 –

+0

@ShubhamKhatri我只是編輯內容。謝謝 – ppppp

回答

0

一種方法是filter兩個陣列和concat在一起:

data1 = [ 
 
    {id:1, name:'Ant'}, 
 
    {id:2, name:'Bird'}, 
 
]; 
 

 
data2 = [ 
 
    {id:2, name:'Bird'}, 
 
    {id:3, name:'Cat'} 
 
]; 
 

 
const filterBird = (data) => data.id !== 2; 
 

 
const filtered1 = data1.filter(filterBird); 
 
const filtered2 = data2.filter(filterBird) 
 

 
const output = filtered1.concat(filtered2); 
 

 
alert(JSON.stringify(output));

相關問題