【问题标题】:Compare an array of objects to another array of objects将一个对象数组与另一个对象数组进行比较
【发布时间】:2018-08-04 04:52:02
【问题描述】:

我有两个数组:

  1. myFriends = [ 0: { uid: 123abc }, 1: { uid:456def }, ];
  2. theirFriends = [ 0: { uid: 123abc }, 1: { uid:789ghi }];

现在我想看看 theirFriends 数组是否有一个与 myFriends 数组中的对象具有相同 uid 的对象,如果有,则设置 theirFriends[object].isFriend = true;如果不是,则将其设置为 false。

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

所以新的 theirFriends 数组应该是:

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

我尝试过:.some()、.map()、.filter()、.forEach(),但我还没有找到可行的解决方案,但每次更新对象时都不会持续运行新值。

【问题讨论】:

    标签: javascript arrays node.js object


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你好,这是我想出来的

      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
          }
      }
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          这是使用forEachsome 的单线:

          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);

          【讨论】:

            猜你喜欢
            • 2017-04-27
            • 1970-01-01
            • 2015-05-23
            • 1970-01-01
            • 1970-01-01
            • 2019-04-06
            • 1970-01-01
            • 2022-08-09
            • 1970-01-01
            相关资源
            最近更新 更多