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


所以,我有两节课

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

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

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

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


1297
2017-11-30 12:24


起源



答案:


你没有展示足够的代码,所以我不确定你如何实例化你的类,但无论如何你可以使用 数组映射函数

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

在操场上的代码


编辑

这可以更短 Object.assign

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

14
2017-11-30 12:30



非常感谢Nitzan - Shilpa Nagavara


答案:


你没有展示足够的代码,所以我不确定你如何实例化你的类,但无论如何你可以使用 数组映射函数

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

在操场上的代码


编辑

这可以更短 Object.assign

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

14
2017-11-30 12:30



非常感谢Nitzan - Shilpa Nagavara


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

游乐场链接


1
2017-11-29 17:03