let user: { id: number, name: string }[] = [
{ "id": 0, "name": "ABC" },
{ "id": 1, "name": "XYZ" }
];
let dataList: { id: number, name: string, address: string , pin: string, comment: string}[] = [];
如果我想将用户数据数组移动到 dataList 数组,我该怎么做?
如果我使用map函数,那么我需要为dataList的其他字段初始化空数据吗?
是的,我需要初始化空数据。
这是一个简单的例子。
let user: { id: number, name: string }[] = [
{ "id": 0, "name": "ABC" },
{ "id": 1, "name": "XYZ" }
];
let dataList: { id: number, name: string, address: string, pin: string, comment: string }[] = user.map(item => {
return {
id: item.id,
name: item.name,
address: "",
pin: "",
comment: ""
};
});
map返回一个数组,所以你只需
dataList=user.map((x:any)=>({
id:x.id,
name:x.name,
address:...
...rest of properties...
})
在“严格模式”下,如果您不想添加具有默认值的所有属性,您应该使用类似的属性
dataList=user.map((x:any)=>({
id:x.id,
name:x.name,
address:...
...not all the properties...
} as { id: number, name: string,
address: string , pin: string,
comment: string})
参见隐式转换“as”。通常您使用界面
export interface dataModel
{ id: number, name: string,
address: string , pin: string,
comment: string}
}
dataList:dataModel=user.map((x:any)=>({
id:x.id,
name:x.name,
} as dataModel)
是的,“地图”如果“有点像”
data=[]
for (let i=0;i<user.length;i++)
data.push({
id:user[i].id
name:user[i].name
})
return data