【问题标题】:How to create dynamically nested objects and object properties in typescript如何在打字稿中创建动态嵌套对象和对象属性
【发布时间】:2021-11-02 03:05:35
【问题描述】:

我想在 typescript 中创建属性和带有属性的嵌套对象,但出现错误。

ERROR TypeError: Cannot read properties of undefined (reading 'bank_account_ownership_verification')

这是我的代码

const account: any = {};

account.documents.bank_account_ownership_verification.files = this.file.value;

【问题讨论】:

  • account.documentsundefined。您无法访问 bank_account_ownership_verification' 的属性 undefined
  • 我明白,但我认为这段代码会动态创建这些对象并允许我添加属性数据或其他对象?
  • 不,它不适合你。您必须一步一步地使用嵌套对象或 Lodash 之类的库来完成。
  • 这样的方括号怎么样:account['documents']['other'] ???我虽然会这样做,但也收到了错误
  • 方括号在这种情况下具有类似的行为。这个问题与 TypeScript 无关。

标签: javascript typescript


【解决方案1】:

无需额外的库,您可以在多个步骤中分配属性

const account: any = {};

account.documents = {};
account.documents.bank_account_ownership_verification = {};
account.documents.bank_account_ownership_verification.files =  ​this.file.value;

或嵌套属性

const account: any = {};

account.documents = { bank_account_ownership_verification: { files: this.file.value } };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 2020-12-01
    • 2020-12-14
    • 2014-04-29
    • 2021-12-06
    • 1970-01-01
    • 2021-06-19
    相关资源
    最近更新 更多