如何从React中的另一个数组的所有元素中过滤数组

时间:2017-09-21 01:45:16

标签: javascript reactjs redux redux-saga

我从这样的API中获取数据。

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个数组的数据,但我不知道如何过滤'数据1'中的'数据2'来获得结果(检查id是否相同' t显示在结果中)

我期待的结果是

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;

});

谢谢

1 个答案:

答案 0 :(得分: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));