将对象数组与另一个对象数组进行比较

时间:2018-02-24 05:09:55

标签: javascript arrays node.js object

我有两个数组:

  1. myFriends = [ 0: { uid: 123abc }, 1: { uid:456def }, ];
  2. theirFriends = [ 0: { uid: 123abc }, 1: { uid:789ghi }];
  3. 现在我想看看他们的theFriends数组是否有一个对象与myFriends数组中的对象具有相同的uid,如果有,则设置itsFriends [object] .isFriend = true;如果它没有,则将其设置为false。

    所以它应该贯穿并最终设置theirFriends[0].isFriend = true。和theirFriends[1].isFriend = false

    所以新的他们的朋友阵列应该是:

    theirFriends = [ 0: { uid: 123abc, isFriend: true }, 1: { uid: 789ghi, isFriend: false }];

    我试过:.some(),。map(),. filter(),. forEach(),但我还没有找到一个有效的解决方案,但每次对象都没有连续运行使用新值更新。

4 个答案:

答案 0 :(得分:1)

首先,您可以将朋友的列表转换为Set。集合仅包含唯一值,并且可以快速检查是否包含值。然后,您可以映射theirFriends并添加新属性。

const myFriendSet = new Set(myFriends.map( friend => friend.uid ))
theirFriends = theirFriends.map( friend => ({
    uid: friend.uid,
    isFriend: myFriendSet.has(friend.uid)
})

答案 1 :(得分:0)

嗨,这是我提出的

var myF = [ { uid: "123abc" }, { uid: "456def" } ];
var theirF = [ { uid: "123abc" }, { uid: "789ghi" }]
//loop through all their friends
for(var i = 0; i < theirF.length; i++)
{
    //loop through all my friends for comparison
    for(var j = 0; j < myF.length; j++)
    {
        if(!theirF[i].isFriend) //if isFriend is not set 
            theirF[i].isFriend = theirF[i].uid == myF[j].uid; //set current theirFriend isFriend propery
    }
}

答案 2 :(得分:0)

以下是使用forEachsome

的oneliner
theirFriends.forEach(tf => tf.isFriend = myFriends.some(mf => mf.uid === tf.uid));

示例:

myFriends = [{uid: '123abc'}, {uid:'456def'}, {uid: '789abc'}, {uid:'789def'}];
theirFriends = [{uid: '123abc'}, {uid:'789ghi'}, {uid: '789def'}, {uid:'000ert'}];

theirFriends.forEach(tf => tf.isFriend = myFriends.some(mf => mf.uid === tf.uid));

console.log(theirFriends);

答案 3 :(得分:0)

Lodash _.isEqual非常适合比较对象。