有没有更好的方法来编写以下内容?:
t = {
name,
color,
teamId: !user?undefined:teamId,
userId: user&&user.id
};
因此,如果定义了用户,那么我希望使用userId,否则使用teamId。
const name = "Me";
const color = "Red";
let user;
let teamId = 10;
t = {
name,
color,
teamId: !user?undefined:teamId,
userId: user&&user.id
};
console.log(t)
user = {id: 1};
teamId = undefined;
t = {
name,
color,
teamId: !user?undefined:teamId,
userId: user&&user.id
};
console.log(t)
答案 0 :(得分:3)
它仍然有点乱,但它只检查用户一次并且更具可读性
return user ? { name, color, "userId": user.id } : { name, color, "teamId": teamId };
答案 1 :(得分:2)
您也可以
{
name,
color,
teamId: user ? undefined : teamId,
userId: user ? user.id : undefined
};