Get JSON Value with Dynamic Key in TypeScript
Small and hopefully helpful snippet.
Problem Scenario
We have Car
data in JSON with an on going updates. modelyear
will be added regularly. We wanted to output model description base on year input by user on a form.
Solution
Convert input to key for lookup
// 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])
See REPL snippet here