我有两个(2)数组,beforeArray
和afterArray
const beforeArray = [
{
id:1,
name:'Alice'
},
{
id:2,
name:'Rabbit'
},
{
id:3,
name:'Queen'
},
{
id:4,
name:'King'
},
];
const afterArray = [
{
id:3,
name:'Queen'
},
];
我正在尝试像下面的数组那样获得beforeArray
和afterArray
的区别:
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
...。
如何从等待的地图和过滤器中获取值?
答案 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.filter和Array.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)