【问题标题】:Creating Properties Dynamically in TypeScript在 TypeScript 中动态创建属性
【发布时间】:2022-01-16 09:03:51
【问题描述】:

我正在使用 DevExpress (devextreme) 的 DataGrid 构建一个数据输入应用程序,并允许用户添加和删除除键列之外的列。我将列配置和用户数据都存储在 SQL 中。用户数据存储为

Key | ColumnName        | ColumnValue
-------------------------------------
1     Company             Apple
1     NumberOfEmployees   12345

然后我旋转数据以发送到网格。

Key | Company | NumberOfEmployees
---------------------------------
1     Apple     12345

当用户更新网格中的一行时,网格会传回一个数据对象,其中包含每列的属性。我正在使用列定义来尝试查找和匹配这些属性,但没有得到预期的结果。

const userColumns: any[] = [
    {
        ColumnName: 'Company'
    }, {
        ColumnName: 'NumberOfEmployees'
    }
];

const returnedFromGridRow: Record<string,any> = {};
returnedFromGridRow.Company = 'Apple';
returnedFromGridRow.NumberOfEmployees = 12345;

let result: Record<string,any> = {};
const results: any = [];

userColumns.forEach(function (value) {
  let x: string = value.ColumnName;
  let y: string = returnedFromGridRow[x];
  
  result = {x:y};
  console.log(result);
  results.push(result);
});

期待

{ "Company" : "Apple" }
{ "NumberOfEmployees" : 12345 }

但得到

{ "x" : "Apple" }
{ "x" : 12345 }

Playground

【问题讨论】:

    标签: typescript dynamic devextreme


    【解决方案1】:

    您用来创建result 对象的方式不起作用,因为它以x 作为键。要动态指定键,请更改创建动态对象的方式,如下所示以获得预期结果:

    userColumns.forEach(function (value) {
      let x: string = value.ColumnName;
      let y: string = returnedFromGridRow[x];
      
      result[x]=y; // This is the change
      console.log(result);
      results.push(result);
    });
    
    

    【讨论】:

      猜你喜欢
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 2022-06-24
      • 2018-12-10
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多