[英]Typescript: Is there a simple way to convert an array of objects of one type to another
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.我有一个需要转换为 ViewItem 数组的 Item 数组。 Currently, I am looping through the array using for, instantiating ViewItem, assigning values to attributes and pushing it to the second array.
目前,我正在使用 for 循环遍历数组,实例化 ViewItem,为属性分配值并将其推送到第二个数组。
Is there a simple way to achieve this using lambda expressions?是否有使用 lambda 表达式实现此目的的简单方法? (similar to C#) Or is there any other means?
(类似于C#) 或者还有其他方法吗?
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 ) ( 操场上的代码)
This can be shorter with Object.assign
:这可以用
Object.assign
缩短:
constructor(item: Item) {
Object.assign(this, item);
}
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));
you can do use something like this.你可以使用这样的东西。
const newdata = olddata.map((x) => {
return { id: Number(x.id), label: x.label };
});
as the converted column will be mapped to the newdata array.因为转换后的列将映射到 newdata 数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.