简体   繁体   English

我如何在 TypeScript 中读取这个对象

[英]How do I read this object in TypeScript

I wanna read this object in typescript but I have no idea how to access keys with dot in them.我想在打字稿中阅读这个对象,但我不知道如何访问其中带有点的键。

{ 
    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',
}

There is an issue with two keys mentioned below, they should be strings下面提到的两个键有问题,它们应该是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"]);

Just use the square brackets syntax like this obj['testSection.id'] for example.例如,只需使用像obj['testSection.id']这样的方括号语法。 It works for every special character that is considered incorrect when in a variable name (like carets, etc...)它适用于在变量名称中被认为不正确的每个特殊字符(如插入符号等...)

使用方括号属性访问:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM