数组映射和过滤ReactJs

时间:2019-05-15 07:35:04

标签: javascript arrays reactjs

我有两个(2)数组,beforeArrayafterArray

const beforeArray = [
   {
    id:1, 
    name:'Alice'
   },
   {
    id:2, 
    name:'Rabbit'
   },
   {
    id:3, 
    name:'Queen'
   },
   {
    id:4, 
    name:'King'
   },
];

const afterArray = [
   {
    id:3, 
    name:'Queen'
   },
];

我正在尝试像下面的数组那样获得beforeArrayafterArray的区别:

const currentArray = [
   {
    id:1, 
    name:'Alice'
   },
   {
    id:2, 
    name:'Rabbit'
   },
   {
    id:4, 
    name:'King'
   },
];

我尝试使用这些方法,但是它仅返回let currentArray = [];中的值:

let currentArray = [];

await afterArray.map(async item => {
    await beforeArray.filter(async find => {
        if (item.id != find.id) {
            await currentArray.map(async less => {
                if (less.id == find.id) {
                    return;
                } else {
                    currentArray = await [...currentArray, find];
                }
            });
        }
    })

console.log(currentArray);

我认为console.log(currentArray)跳过了await...。 如何从等待的地图和过滤器中获取值?

2 个答案:

答案 0 :(得分:2)

尝试像这样使用Array.prototype.some过滤数组:

const beforeArray = [{
    id: 1,
    name: 'Alice'
  },
  {
    id: 2,
    name: 'Rabbit'
  },
  {
    id: 3,
    name: 'Queen'
  },
  {
    id: 4,
    name: 'King'
  },
];

const afterArray = [{
  id: 3,
  name: 'Queen'
}];

const currentArray = beforeArray.filter(x => {
  return afterArray.some(y => y.id !== x.id && y.name !== x.name);
});

console.log(currentArray);

答案 1 :(得分:-1)

在等待承诺解决之前,您不应该使用async / await。

您可以使用Array.prototype.filterArray.prototype.find

过滤数组

const beforeArray = [
	{
	 id:1, 
	 name:'Alice'
	},
	{
	 id:2, 
	 name:'Rabbit'
	},
	{
	 id:3, 
	 name:'Queen'
	},
	{
	 id:4, 
	 name:'King'
	},
];

const afterArray = [
	{
	 id:3, 
	 name:'Queen'
	},
];

let out = beforeArray.filter(({id, name}) => !afterArray.find(r => r.id === id && r.name === name));

console.log(out)