我正在寻找一种更优雅的方式来编写该代码:
Observable.of(
{field: "title"},
{field: "referenceId", key: "refid"},
{field: "app"},
{field: "user"},
{field: "action"},
{field: "expiresAt", key: "expiration"},
{field: "timestamp"}
)
.pipe(
map(field => {
if (!field.key) {
return { ...field, key: field.field, sorteable: true };
}
else {
return { ...field, sorteable: true };
}
})
);
答案 0 :(得分:2)
您可以尝试像这样使用三元条件运算符?:
.pipe(
map(field =>
field.key ? { ...field, sorteable: true } : { ...field, key: field.field, sorteable: true }
);
您还可以通过省略else条件来简化代码:
.pipe(
map(field => {
let temp = { ...field, sorteable: true }
if(!field.key) {
temp = {...temp, key: field.field}
}
return temp
}
);
您甚至可以结合两种解决方案:
.pipe(
map(field => {
let temp = { ...field, sorteable: true }
return field.key ? temp : {...temp, key: field.field}
}
);