![](/img/trans.png)
[英]compare two arrays of Objects in JavaScript and if true save new items to MongoDB
[英]Compare Two Arrays Of Objects and return a new array if value is true in Javascript
我需要比較 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
},
]
如果invited
為true
,我需要返回一個新數組。
像這樣的東西:
const newArray = [
{
userId: 'u12p3',
name: 'Goku',
invited: true
},
{
userId: 'ufisj',
name: 'Goten',
invited: false
},
{
userId: 'uefi3',
name: 'Vegeta',
invited: true
},
]
知道如何實現這一目標嗎? 請幫忙
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);
使用過濾來實現:
invitedFriends = allFriends.filter(friend => friend.invited==true);
因為您還需要,invited 行,所以邏輯是將相同的數據從受邀朋友替換為 allFriends(按 id 比較)
我們在 allfriends 上循環,然后查找 allfriend(n).id 是否在受邀朋友上找到,如果找到,然后推送受邀朋友(found),如果不只是推送 allfriend(n)
所以在一行中你可以使用
let x = allFriends.map( af => inviteFriends.find( x => x.userId === af.userId) || af );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.