typescript 打字稿:是否有一种简单的方法可以将一种类型的对象数组转换为另一种类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40888305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:29:49  来源:igfitidea点击:

Typescript: Is there a simple way to convert an array of objects of one type to another

arraystypescripttype-conversiontypescript2.0

提问by Shilpa Nagavara

So, I have two classes

所以,我有两个班级

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

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

I have an array of Item that needs to be converted into an array of ViewItem. Currently, I am looping through the array using for, instantiating ViewItem, assigning values to attributes and pushing it to the second array.

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

Is there a simple way to achieve this using lambda expressions? (similar to C#) Or is there any other means?

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

回答by Nitzan Tomer

You haven't showed enough of your code, so I'm not sure how you instantiate your classes, but in any case you can use the 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)

操场上的代码



Edit

编辑

This can be shorter with Object.assign:

这可以更短Object.assign

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

回答by cyberpirate92

An alternate method is to use Object.keys,

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

Usage:

用法:

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

Playground link

游乐场链接