gpt4 book ai didi

javascript - Angular 6,从对象中获取新对象

转载 作者:行者123 更新时间:2023-11-28 16:57:03 24 4
gpt4 key购买 nike

我的 list

defaultUsers: any[] = [
{id: 31, name: "A"},
{id: 32, name: "B"},
{id: 33, name: "C"},
{id: 34, name: "D"},
{id: 35, name: "E"},
{id: 36, name: "F"},
{id: 37, name: "G"},
{id: 38, name: "H"},
];

onlineUsers: any[]= [
{userid: 31, platform: 'web'},
{userid: 31, platform: 'mobil'},
{userid: 32, platform: 'mobil'},
];

users: any[];

我的函数,


test(){
let isOnline: boolean, isWeb: boolean, isMobile: boolean;

this.users = this.defaultUsers.map(user=>{
isOnline = this.onlineUsers.some((onlineUser: { userid: number; })=> onlineUser.userid == user.id);

-- ( ! help-> I could not build the structure in my head) --

return {...user, online: isOnline }
});

console.log(this.users)
}

我想要得到:

[
{id: 31, name: "A", mobile: true, web: true, online: true },
{id: 32, name: "B", mobile: true, web: false, online: true },
{id: 33, name: "C", mobile: false, web: false, online: false },
{id: 34, name: "D", mobile: false, web: false, online: false },
{id: 35, name: "E", mobile: false, web: false, online: false },
{id: 36, name: "F", mobile: false, web: false, online: false },
{id: 37, name: "G", mobile: false, web: false, online: false },
{id: 38, name: "H", mobile: false, web: false, online: false },
]

如何才能以最准确和最高效的方式确保这一点?你能帮助我吗?我想用我手中的物体得到我想要的物体。

最佳答案

您可以使用 .filter()onlineUsers 检索用户并查找平台类型:

  test() {
let isOnline: boolean, isWeb: boolean, isMobile: boolean;

this.users = this.defaultUsers.map((u) => {
const users = this.onlineUsers.filter((onlineUser: { userid: number; platform: string; }) => onlineUser.userid == u.id);

const isOnline = !!users.length;
const isWeb = users.some((usr) => usr.userid === u.id && usr.platform === 'web');
let isMobile = users.some((usr) => usr.userid === u.id && usr.platform === 'mobil');

return { ...u, online: isOnline, web: isWeb, mobile: isMobile }
});

console.log(this.users)
}

现场演示:here

关于javascript - Angular 6,从对象中获取新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58859881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com