rxjs:地图添加字段

时间:2019-05-17 09:53:12

标签: typescript rxjs

我正在寻找一种更优雅的方式来编写该代码:

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

1 个答案:

答案 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}
        }
    );