【问题标题】:How do I read this object in TypeScript如何在 TypeScript 中读取此对象
【发布时间】:2021-01-01 09:17:01
【问题描述】:

我想在打字稿中阅读这个对象,但我不知道如何访问带有点的键。

{ 
    id: '2db232c9-87ee-4cde-ace1-23bc18722f2d',
    code: 'BPT',
    name: 'Basic Programming',
    basePrice: 200,
    description: null,
    isCalibration: false,
    createdAt: 2020-09-14T15:35:51.526Z,
    updatedAt: 2020-09-14T15:35:51.526Z,
    deletedAt: null,
    'testSection.id': 'f7c228aa-224e-4376-8170-8135077a9e6b',
    'testSection.testTypeId': '2db232c9-87ee-4cde-ace1-23bc18722f2d',
    'testSection.testSectionCategory.categoryName': 'DSA-CAT2',
}

【问题讨论】:

    标签: javascript node.js typescript sequelize.js


    【解决方案1】:

    例如,只需使用像 obj['testSection.id'] 这样的方括号语法。它适用于在变量名中被认为不正确的每个特殊字符(如插入符号等......)

    【讨论】:

    • 实际上我在一个数组中有很多结果。因此,当我尝试 arr[0]['testSection.id'] 时,它会给出错误提示标识符预期
    • @KunalShukla 对我来说,即使是数组中的对象,它也能正常工作。假设您的代码是正确的,因为我必须在 createdAtupdatedAt 属性中添加引号。
    【解决方案2】:

    使用方括号属性访问:

    console.log(obj['testSection.id']) // 'f7c228aa-224e-4376-8170-8135077a9e6b'
    

    【讨论】:

      【解决方案3】:

      下面提到的两个键有问题,它们应该是strings

      createdAt: '2020-09-14-T15:35:51.526Z',
      updatedAt: '2020-09-14-T15:35:51.526Z',
      

      let obj = { 
          id: '2db232c9-87ee-4cde-ace1-23bc18722f2d',
          code: 'BPT',
          name: 'Basic Programming',
          basePrice: 200,
          description: null,
          isCalibration: false,
          createdAt: '2020-09-14-T15:35:51.526Z',
          updatedAt: '2020-09-14-T15:35:51.526Z',
          deletedAt: null,
          'testSection.id': 'f7c228aa-224e-4376-8170-8135077a9e6b',
          'testSection.testTypeId': '2db232c9-87ee-4cde-ace1-23bc18722f2d',
          'testSection.testSectionCategory.categoryName': 'DSA-CAT2',
      }
      
      console.log(obj["testSection.id"]);
      console.log(obj["testSection.testTypeId"]);
      console.log(obj["testSection.testSectionCategory.categoryName"]);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-28
        • 1970-01-01
        • 2021-02-07
        • 2020-08-08
        • 2019-11-01
        • 2019-12-06
        • 2022-11-29
        • 2019-04-19
        相关资源
        最近更新 更多