[英]Compare Two Arrays Of Objects and return a new array if value is true in Javascript
I need to compare 2 arrays我需要比较 2 arrays
const inviteFriends = [
{
userId: 'u12p3',
name: 'Goku',
invited: true
},
{
userId: 'uefi3',
name: 'Vegeta',
invited: true
}
]
const allFriends = [
{
userId: 'u12p3',
name: 'Goku',
invited: false
},
{
userId: 'ufisj',
name: 'Goten',
invited: false
},
{
userId: 'uefi3',
name: 'Vegeta',
invited: false
},
]
An if invited
is true
I need to return a new array.如果invited
为true
,我需要返回一个新数组。
Something like this:像这样的东西:
const newArray = [
{
userId: 'u12p3',
name: 'Goku',
invited: true
},
{
userId: 'ufisj',
name: 'Goten',
invited: false
},
{
userId: 'uefi3',
name: 'Vegeta',
invited: true
},
]
Any idea how can I achieve this?知道如何实现这一目标吗? Help please请帮忙
const inviteFriends = [ { userId: 'u12p3', name: 'Goku', invited: true }, { userId: 'uefi3', name: 'Vegeta', invited: true } ] const allFriends = [ { userId: 'u12p3', name: 'Goku', invited: false }, { userId: 'ufisj', name: 'Goten', invited: false }, { userId: 'uefi3', name: 'Vegeta', invited: false }, ]; const newArr = allFriends.map((friend) => { const found = inviteFriends.find((invited) => { return invited.userId === friend.userId }); return {...friend, ...found}; }); console.log(newArr);
Use filtering to achieve that:使用过滤来实现:
invitedFriends = allFriends.filter(friend => friend.invited==true);
since you also need the,invited row, so the logic is to replace the same data from invitedFriends to allFriends (compare by id)因为您还需要,invited 行,所以逻辑是将相同的数据从受邀朋友替换为 allFriends(按 id 比较)
we loop on the allfriends then find if allfriend(n).id found on invitedFriend if found then push invitedFriend(found) if not just push the allfriend(n)我们在 allfriends 上循环,然后查找 allfriend(n).id 是否在受邀朋友上找到,如果找到,然后推送受邀朋友(found),如果不只是推送 allfriend(n)
so in one line you can use所以在一行中你可以使用
let x = allFriends.map( af => inviteFriends.find( x => x.userId === af.userId) || af );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.