所以,我有两个班级
Item { name: string; desc: string; meta: string}
ViewItem { name: string; desc: string; hidden: boolean; }
我有一个Item数组,需要转换成一个ViewItem数组。 目前,我正在使用for循环遍历数组,实例化ViewItem,给属性赋值并将其推送到第二个数组中。
是否有一种简单的方法可以使用lambda表达式来实现这个目标?(类似于C#) 或者还有其他方法吗?
所以,我有两个班级
Item { name: string; desc: string; meta: string}
ViewItem { name: string; desc: string; hidden: boolean; }
我有一个Item数组,需要转换成一个ViewItem数组。 目前,我正在使用for循环遍历数组,实例化ViewItem,给属性赋值并将其推送到第二个数组中。
是否有一种简单的方法可以使用lambda表达式来实现这个目标?(类似于C#) 或者还有其他方法吗?
你没有展示足够的代码,所以我不确定你如何实例化你的类,但在任何情况下,你都可以使用数组 map 函数:
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);
}
你可以像这样使用它。
const newdata = olddata.map((x) => {
return { id: Number(x.id), label: x.label };
});
由于转换后的列将映射到新数据数组中。
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));
{ id: Number(...), label: ... }
与问题中所需的ViewItem
类有何关联?2016年和2017年的两个现有答案也使用了Array.map,但实际上它们回答了问题,因为它们实际上返回了ViewItem
实例。 - Martijn Pietersnewdata
是ViewItem
数组。也许这个答案可以使用SO的精确参数命名。 - Vivek Shukla