打字稿:是否有一种简单的方法可以将一种类型的对象数组转换为另一种类型 [英] Typescript: Is there a simple way to convert an array of objects of one type to another

查看:102
本文介绍了打字稿:是否有一种简单的方法可以将一种类型的对象数组转换为另一种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有两个类

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

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

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

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.

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

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

推荐答案

您没有显示足够的代码,所以我不确定如何实例化类,但是无论如何您都可以使用数组地图函数

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

操场上的代码

Object.assign

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

这篇关于打字稿:是否有一种简单的方法可以将一种类型的对象数组转换为另一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆