简体   繁体   中英

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

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. 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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