打字稿:有没有一种简单的方法可以将一种类型的对象数组转换为另一种类型
Typescript: Is there a simple way to convert an array of objects of one type to another
所以,我有两个 类
Item { name: string; desc: string; meta: string}
ViewItem { name: string; desc: string; hidden: boolean; }
我有一个 Item 数组需要转换成一个 ViewItem 数组。
目前,我正在使用 for 遍历数组,实例化 ViewItem,为属性赋值并将其推送到第二个数组。
是否有使用 lambda 表达式实现此目的的简单方法? (类似于 C#)
还是有其他办法?
你没有展示足够的代码,所以我不确定你是如何实例化你的 类,但无论如何你可以使用 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);
}
另一种方法是使用 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));
你可以使用这样的东西。
const newdata = olddata.map((x) => {
return { id: Number(x.id), label: x.label };
});
因为转换后的列将映射到新数据数组。
所以,我有两个 类
Item { name: string; desc: string; meta: string}
ViewItem { name: string; desc: string; hidden: boolean; }
我有一个 Item 数组需要转换成一个 ViewItem 数组。 目前,我正在使用 for 遍历数组,实例化 ViewItem,为属性赋值并将其推送到第二个数组。
是否有使用 lambda 表达式实现此目的的简单方法? (类似于 C#) 还是有其他办法?
你没有展示足够的代码,所以我不确定你是如何实例化你的 类,但无论如何你可以使用 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);
}
另一种方法是使用 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));
你可以使用这样的东西。
const newdata = olddata.map((x) => {
return { id: Number(x.id), label: x.label };
});
因为转换后的列将映射到新数据数组。