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 more →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay