打字稿:有没有一种简单的方法可以将一种类型的对象转换为另一种类型

时间:2016-11-30 12:24:20

标签: arrays typescript type-conversion typescript2.0

所以,我有两个班级

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

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

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

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

3 个答案:

答案 0 :(得分:23)

您还没有显示足够的代码,因此我不确定您如何实例化您的课程,但无论如何您都可以使用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);
}

答案 1 :(得分:1)

另一种方法是使用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

答案 2 :(得分:1)

你可以使用这样的东西。

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

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

相关问题