Converting JSON property into a Map key in Typescript: A guide

I need help with parsing a JSON property as a Map key. The JSON string I am working with is:

const jsonString = `{
    "DDBProps": {
      "us-east-1": {
        "test": "2",
        "prod": "100"
      },
      "us-west-2": {
        "test": "2",
        "prod": "100"
      }
    },
    "DDBProps2": {
      "us-east-1": {
        "test": "2",
        "prod": "200"
      },
      "us-west-2": {
        "test": "2",
        "prod": "200"
      }
    }
}`

I want the properties like "DDBProps", "DDBProps2" to act as keys in a Map, and the values to be nested Maps. Essentially, something like

Map<string, Map<string, Map<string, string>>>
. This nested map structure will allow me to retrieve numerical values (e.g. "2", "100", "200" in this JSON) based on inputs such as: DDBPropsType, region, stage.

To achieve this, I have declared interfaces:

interface ThroughputMap {
    throughputMappings: Map<string,RegionMap>
}

interface RegionMap {
    regionMappings: Map<string, StageMap>
}

interface StageMap {
    stageMappings: Map<string, string>
}

// parse
const ddbScaleMap: ThroughputMap = JSON.parse(ddbScalingMappingsJson);

However, I'm facing issues with parsing the JSON into the correct structure:

console.log(ddbScaleMap)
// output below
{
    "DDBProps": {
      "us-east-1": {"test": "2","prod": "100"},
      "us-west-2": {"test": "2","prod": "100"}
    },
    "DDBProps2": {
      "us-east-1": {"test": "2","prod": "200"},
      "us-west-2": {"test": "2","prod": "200"}
    }
}


console.log(ddbScaleMap.throughputMappings) // output undefined

The problem lies in not being able to parse the property as a Map key.

Things I've attempted:

const ddbScaleMap = new Map<string, Map<string, Map<string, string>>>(Object.fromEntries(JSON.parse(jsonString)))

This method did not correctly parse the nested value. For example, calling

ddbScaleMap.get("DDBProps").get("us-west-2");
does not work as expected.

Answer №1

It seems that there is a clever way to access nested values without the need to convert them into a map. In TypeScript, you can make use of keyof typeof to easily access nested values like so:

function retrieveThroughputByKey(key: string, region: string, stage: string): number {
    const defaultThroughputValue = 1;

    const regionToStageMapping = dataObject[key as keyof typeof dataObject];
    const stageToThroughputMapping = regionToStageMapping[region as keyof typeof regionToStageMapping];
    const throughputString = stageToThroughputMapping[stage as keyof typeof stageToThroughputMapping];
    const throughput = Number(throughputString);

    return throughput || defaultThroughputValue;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing a JavaScript object that may be undefined to a pug template in Node.js

My journey requires transferring a set of JavaScript objects to the pug template. router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeE ...

Establish connections between different models using a unique key found within the attributes of a Swift Decodable object

Consider the following JSON data: [{ "name": "TV", "room": "Living Room" }, { "name": "LightBulb 1", "room": "Living Room" } ] struct Room: Decodable { let name: String let devices: [Device] } struct Devic ...

The image located at 'http://localhost:8080/favicon.ico' was unable to load due to a violation of its content

I am currently developing a JavaScript app called food2fork. I encountered an issue when the AJAX call API promise is fulfilled and the results (recipes) are rendered. However, when I click on one of the recipes, it moves to the next page and displays: ...

augmentable form that can be expanded flexibly

Perhaps I'm missing something really simple here, but I just can't seem to figure this out. I'm attempting to create a form that can dynamically extend. The issue I'm facing is that I can't get this particular code to function: & ...

Converting a string to null with PHP's json_encode

I'm currently troubleshooting a problem with a PHP script I've been working on. The script utilizes the phpseclib library to encrypt a password using a public RSA key provided by an ASP.NET application. Everything appears to be functioning proper ...

Guide on utilizing vue-router and router-link for managing links that are dynamically generated within jquery modules like datatables

I spent some time trying to "integrate" datatables.net (https://datatables.net/) into a Vue app. After some trial and error, I came across advice suggesting not a direct integration approach, but rather utilizing jquery modules as they are and "hooking" t ...

Attempting to refresh a function when an image is clicked

I'm facing an issue with reloading a function in my code that involves a JSON file. The function should display the correct item on the page when you click on a related product image, but I haven't been able to get it working properly. Any guidan ...

Is it possible for me to create personalized color definitions that I can seamlessly use across CSS, JavaScript, and HTML files?

I'm currently using a shade of blue throughout my app, and I find myself repeatedly copying and pasting the color code in my CSS styles. Is there a way to create a constant for this specific color that can be shared across my CSS, HTML, and JavaScript ...

How can I verify if an SVG file has a reliable source? (having troubles converting SVG to canvas)

While attempting to use an SVG generated by a chart plugin (https://wordpress.org/plugins/visualizer/), I am facing issues retrieving the source of the SVG-image being created. Interestingly, when using other SVGs with the same code, everything works perfe ...

What is the best way to detect clicks on numerous images?

Seeking a solution for handling click events on multiple imagemaps within an iOS uiwebview to manage scaling across various iOS devices. While the click handler functions properly for the first image, it fails to work for subsequent images. How can I ensur ...

Javascript function that sets the opacity to 0

Hello everyone, I'm new to SO and seeking some guidance on improving my post! I have a function that sets the opacity of an element to 0 in order to clear it. While this works fine, it becomes burdensome when dealing with multiple elements that requi ...

Organizing JSON data in an array for display in a UITableView

Here's a JSON Array containing information about some movies: { "id": 36, "name": "The Shawshank Redemption", "year": 1994, "rating": 9.196 }, { "id": 45, "name": "The Green Mile", "year": 1999, "rating": 9.064 }, { "id": 48, "na ...

The search bar automatically conceals any results that are not actively being searched for

I am currently looking to only display or store local data related to the words "Apple" and "Car." Specifically, if a user types in "apple", I want the results to show the word "apple" while hiding the word "car", and vice versa. Currently, each item has ...

Executing functions on Angular scope within Underscore Template

Having an underscore template being invoked from an Angular controller, there is a dropdown in the template and an onchange function called on the dropdown. Despite several attempts to get the method triggered in the onchange event, using this code <se ...

Utilizing JQuery to select list items for pagination purposes

I am currently working on a pagination script and everything seems to be functioning well, except for one minor issue. I am struggling with triggering an action when the page number (li) is clicked. The pagination data is being retrieved via ajax and disp ...

Extension for Chrome: Automatically transfer downloaded files to a designated input field

I have developed a small chrome extension to migrate images, which consists of 5 files: popup.html - the plugin's HTML document This file contains HTML buttons and a script link to settings.js, which listens for the image download button to be clic ...

Can anyone assist me with creating a reusable component for `next-intl` that can be

Let me explain what I'm looking for. If you're not familiar with next-intl, it's a package designed to provide internationalization support for Next.js applications. The Issue: The developer of next-intl is working on a beta version that su ...

reduce input to 2 characters using jQuery

Is there a way to trim the input text down to just the first two characters when a button is clicked? For example, if I enter "BT2J43" into the input field, can it be automatically shortened to "BT" upon clicking the button? I'm new to learning jQue ...

Having trouble with UseSelector in React Redux?

I am currently working on a exercise to better understand the react-redux process, but I seem to have hit a roadblock. Any assistance would be greatly appreciated. One interesting observation is that when I subscribe and log the store into the console, it ...

The specified route type does not comply with the NextJS route requirements, resulting in an authentication error

Recently, I have encountered an issue with NextJS routes while working on an ecommerce project. I am seeking guidance to resolve this issue, specifically related to my route.ts file which interacts with NextAuth for providers like Google. During developmen ...