打字稿:是否有一种简单的方法可以将一种类型的对象数组转换为另一种类型
问题描述:
所以,我有两个类
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);
}