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 Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more