我有一个界面栏。
interface column {
field: string
label: string
}
所以一排列将是:
const cols = [{
label: 'First Name',
field: 'fname',
},
{
label: 'Last Name',
field: 'lname',
},
{
label: 'Email',
field: 'email',
}]
数据将是数据行的数组。
const data:{}[] = [{
fname: 'bob', lname: 'dylan', email: '[email protected]',
fname: 'van', lname: 'halen', email: '[email protected]'
}]
[有没有一种方法可以将数据的键(即[fname,lname,email])强制为相应cols [n] ['field']的值?预先感谢。
这是一个棘手的问题。有
interface Column {
field: string
label: string
}
[我们可以定义RowObject
,此外,仅出于示例的考虑,具有Row
属性和column
本身的row
。
interface RowObject {
[key: string]: string;
}
interface Row {
cols: Column[];
row: RowObject;
}
现在,我们应该定义一个函数来原型化新对象。
const createRowBlueprint = (cols: Column[]): Row => {
return {
cols: [...cols],
row: cols.map(c => c.field)
.reduce((prop: RowObject, prev: string) => (prop[prev] = '', prop), {})
};
};
我刚刚定义了Row
接口,以动态访问“真实行对象”属性,像这样
const row = createRowBlueprint(cols);
row.cols.forEach(col => {
const { field } = col;
const value = row.row[field];
console.log(`Field ${field} binded to ${value}`);
});
给出您的columns
集合,将输出以下内容
{
cols: [
{ label: 'First Name', field: 'fname' },
{ label: 'Last Name', field: 'lname' },
{ label: 'Email', field: 'email' }
],
row: { fname: '', lname: '', email: '' }
}
Field fname binded to
Field lname binded to
Field email binded to
显然,我将默认值设置为空字符串。但是,有效的证明是从字段访问的值不是undefined
。
最后,这种方法不是安全类型。但是,据我所知,目前,Typescript在编译时不支持动态类型定义。因此,这是一个棘手的解决方法。
希望有帮助。