DEV Community

NETIC
NETIC

Posted on • Edited on

1 1

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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs