DEV Community

NETIC
NETIC

Posted on • Edited on

Get JSON Value with Dynamic Key in TypeScript

Small and hopefully helpful snippet.

Scenario: You have an on going update of JSON of Car data which has modelyear being added regularly. You wanted to output model description base on year as an input.

// Get JSON Value with dynamic key const vehicle = { "category": "car", "brand": "SupaDupa", "modelYear": { "2000": "SD-S", "2020": "SD-M", "2030": "SD-A", "2040": "SD-R", "2050": "SD-T" } } type ObjectKey = keyof typeof vehicle.modelYear; const year = '2020' as ObjectKey // set value of dynamic key console.log(vehicle.modelYear[year]) 
Enter fullscreen mode Exit fullscreen mode

I had Original Snippet here

Top comments (0)