【问题标题】:Typescript: Is there a simple way to convert an array of objects of one type to another打字稿:有没有一种简单的方法可以将一种类型的对象数组转换为另一种类型
【发布时间】:2016-11-30 12:24:20
【问题描述】:

所以,我有两个课

Item { name: string; desc: string; meta: string}

ViewItem { name: string; desc: string; hidden: boolean; }

我有一个 Item 数组,需要转换为 ViewItem 数组。 目前,我正在使用 for 循环遍历数组,实例化 ViewItem,将值分配给属性并将其推送到第二个数组。

有没有一种简单的方法可以使用 lambda 表达式来实现这一点? (类似于 C#) 还是有其他方法?

【问题讨论】:

    标签: arrays typescript type-conversion typescript2.0


    【解决方案1】:

    你可以使用这样的东西。

    const newdata = olddata.map((x) => {
            return { id: Number(x.id), label: x.label };
          });
    

    因为转换后的列将映射到 newdata 数组。

    【讨论】:

      【解决方案2】:

      你没有展示足够的代码,所以我不确定你如何实例化你的类,但无论如何你可以使用array map function

      class Item {
          name: string;
          desc: string;
          meta: string
      }
      
      class ViewItem {
          name: string;
          desc: string;
          hidden: boolean;
      
          constructor(item: Item) {
              this.name = item.name;
              this.desc = item.desc;
              this.hidden = false;
          }
      }
      
      let arr1: Item[];
      let arr2 = arr1.map(item => new ViewItem(item));
      

      (code in playground)


      编辑

      Object.assign 可以更短:

      constructor(item: Item) {
          Object.assign(this, item);
      }
      

      【讨论】:

      • 非常感谢尼赞
      【解决方案3】:

      另一种方法是使用Object.keys

      class Item {
          name: string;
          desc: string;
          meta: string
      }
      
      class ViewItem {
          name: string;
          desc: string;
          hidden: boolean;
      
          // additional properties
          additionalProp: boolean;
      
          constructor(item: Item) {
              Object.keys(item).forEach((prop) => { this[prop] = item[prop]; });
      
              // additional properties specific to this class
              this.additionalProp = false;
          }
      }
      

      用法:

      let arr1: Item[] = [
          {
              name: "John Doe",
              desc: "blah",
              meta: "blah blah"
          }
      ];
      let arr2: ViewItem[] = arr1.map(item => new ViewItem(item));
      

      Playground link

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-28
        • 2011-09-24
        • 2021-02-04
        • 1970-01-01
        • 1970-01-01
        • 2021-04-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多