Angular 2+比较2个数组之间的差异

时间:2019-10-18 12:26:21

标签: arrays angular filter

我拥有的数组

const users = [
      { id: 1, name: "field 1" },
      { id: 2, name: "field 2" },
      { id: 3, name: "field 3" },
      { id: 4, name: "field 4" },
    ];
    const onlineUsers = [
      { id: 1, name: "field 1" },
      { id: 3, name: "field 3" }
    ];

我想通过比较两个系列来查找在线和离线版本

我想这样做:

const userLists = [
      { id: 1, name: "field 1", online: true },
      { id: 2, name: "field 2", online: false },
      { id: 3, name: "field 3", online: true },
      { id: 4, name: "field 4", online: false },
    ];

3 个答案:

答案 0 :(得分:0)

使用Array.mapArray.some

const users = [
      { id: 1, name: "field 1" },
      { id: 2, name: "field 2" },
      { id: 3, name: "field 3" },
      { id: 4, name: "field 4" },
    ];
    const onlineUsers = [
      { id: 1, name: "field 1" },
      { id: 3, name: "field 3" }
    ];
    
    var retVal=users.map(u=>{
    var isOnline=onlineUsers.some(ou=> ou.id==u.id);//this will check if onlineUsers have some record with given userid
    return {...u,online:isOnline}
    })
    
    console.log(retVal)

答案 1 :(得分:0)

您可以遍历用户列表,并可以使用find找出在线用户,并只需在在线userList中push即可找到它。

const users = [
      { id: 1, name: "field 1" },
      { id: 2, name: "field 2" },
      { id: 3, name: "field 3" },
      { id: 4, name: "field 4" },
    ];
    const onlineUsers = [
      { id: 1, name: "field 1" },
      { id: 3, name: "field 3" }
    ];

const userLists  = [];

users.forEach(user => {
  if(onlineUsers.find(q => q.id == user.id)){
    userLists.push({
      id: user.id,
      name: user.name,
      online: "true"
    })
  }
  else{
    userLists.push({
      id: user.id,
      name: user.name,
      online: "false"
    })
  }
})

console.log(userLists);

答案 2 :(得分:0)

使用Array.indexOf()JSON.strigify()的方法快一点

const onlineUsers = JSON.stringify([
  { id: 1, name: "field 1" },
  { id: 3, name: "field 3" }
]);  

const userList = users.map(user => 
  ({ 
     ...user,
     online: onlineUsers.indexOf(JSON.stringify(user)) > -1
   })
);

,如果您既不想更改原始的onlineUsers数组也不想声明另一个变量:

const userList = users.map(user => 
  ({ ...user, online: JSON.stringify(onlineUsers).indexOf(JSON.stringify(user)) > -1 })
);