Creating a map in Typescript initialized with a JSON object

In my Typescript class, there is a map that I'm trying to initialize:

public map:Map<string,string>;
constructor() {
  let jsonString = {
    "peureo" : "dsdlsdksd"
  };
  this.map = jsonString;
}

The issue I'm encountering is that the initialization isn't functioning as expected.

The jsonString variable will contain data received from a Java Object serialized to Json.

If anyone has any advice or solutions, I would greatly appreciate it. Thank you!

Answer №1

To populate the map with object members, you need to iterate through each member:

public dataMap: Map<string, string> = new Map<string, string>();

constructor() {
    let jsonData = {
        "apple": "red",
        "banana": "yellow"
    };

    for (let key in jsonData) {
        this.dataMap.set(key, jsonData[key]);
    }
}

Answer №2

Initially, I marked this question as a potential duplicate. However, upon further consideration, I realized that there are significant differences between plain JavaScript and TypeScript, making it a unique question ... my mistake!

After deserialization, the JSON results in a plain object.

Map is a distinct class, and converting a plain object into a Map object is not straightforward.

The Map documentation specifies that its constructor accepts:

An Array or other iterable object containing key-value pairs. Each pair is added to the new Map; null values are treated as undefined.

Unfortunately, plain objects do not support iteration, preventing direct conversion to a Map.

One approach is to iterate over the properties, validate if they are strings, and then insert them into the map.

let convertObjectToStringPropertiesToMap = (obj: Object) => {
    let map = new Map();

    for (let key in obj) {
        let val = obj[key];

        if (typeof val == "string")
            map.set(key, val);
    }
};

This would result in code similar to the following:

let obj = {
    "example" : "sample"
};

let convertObjectToStringPropertiesToMap = (obj: Object) => {
    let map = new Map();

    for (let key in obj) {
        let val = obj[key];

        if (typeof val == "string")
            map.set(key, val);
    }

    return map;
};

let map = convertObjectToStringPropertiesToMap(obj);

document.getElementById("output").innerHTML = map.get("example");

You can see this in action on jsFiddle.

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

Ways to substitute the v-model pattern with react hooks

Transitioning my application from Vue to React. In Vue 2, using v-model on a component was similar to passing a value prop and emitting an input event. To change the prop or event names to something different in Vue, a model option needed to be added to t ...

Effective Strategies for Preserving Form Input Values during Validation Failure in Spring MVC

I am currently working on validating user input, and I want the user's input fields to be retained in case of any validation errors. This is how I have set up my input fields: <form:input path="firstName" class="text short" id="firstName" value=" ...

I'm experiencing an issue where Angular Directives are not rendering properly when fetched from a JSON

I've been working on creating a front end that pulls content from a WordPress CMS. I've successfully used the WP REST API plugin to retrieve JSON data from my WordPress site and display the HTML content using 'ng-bind-html'. However, I ...

Development of a chart application involving frontend and backend components, utilizing chartjs for data visualization, mongodb for storage

As a beginner in generating charts using the ajax mechanism and chartjs, I've encountered an issue where the graphs are being plotted incorrectly. Any guidance on how to improve would be greatly appreciated. Thank you! Here is my JavaScript code for ...

The error message "string indices must be integers" is common when working with

While learning Python, I encountered an issue with the following question. Despite attempting various solutions found online, none seem to work. Every time I compile the code, it gives me an error saying: "string indices must be integers". Can anyone provi ...

Converting MySQL tables into JSON files

Currently, I am working on a remote CentOS machine without graphical access, relying solely on the terminal. On this machine, there is a MySQL database with a table from which I am fetching the first 10 entries using the command SELECT * FROM MY_TABLE LIMI ...

jQuery can be used to obtain the label for a checkbox with a particular value

Currently, I am facing an issue with retrieving the label for a checkbox using jQuery. Let me provide you with the relevant HTML code: <div class="checkbox"> <label><input type="checkbox" name="cb_type[]" value="sold" >Sold</label ...

What is the best way to receive a JSON response in CodeIgniter view after making an AJAX call?

I have been attempting to retrieve a response from the CodeIgniter controller within my view, but unfortunately, I have not been successful. Below is the JavaScript code in my file: // User enters their email address to check against the database. $(" ...

Trouble with json_encode when dealing with a multidimensional array

I've been struggling to retrieve results from 2 queries in JSON format. Even though var_dump($data) is showing the data, using json_encode either returns empty results or doesn't work at all. $data = array(); $array_articles = array(); $sql_arti ...

Is there a different method for looping in JSX besides .map()?

In my JSX code, I am attempting to display a specific value based on certain conditions. The current code snippet checks if the 'item.result' exists and has a length greater than 0. If so, it maps through the 'item.result' array and dis ...

Deleting specific arrays by selecting checkboxes and removing them in Vue.js

<script> import { datalist } from "./datalist"; export default { name: "HelloWorld", components: {}, data() { return { items: datalist, }; }, methods: { deleteEvent(id) { this.items = this.items.filter((e) => e.id ...

Extract core object from array of objects with lodash or javascript

In my code, I have an array of objects that each contain a base object with a set of values. My goal is to remove the base object from all the data and achieve the Expected result shown below. Here is an example of the array: [ { "100": { ...

Create a d.ts file in JavaScript that includes a default function and a named export

While working on writing a d.ts file for worker-farm (https://github.com/rvagg/node-worker-farm), I encountered an issue. The way worker-farm handles module.exports is as follows: module.exports = farm module.exports.end = end When trying to replica ...

An uncaught security error occurred when attempting to execute the 'pushState' function on the 'History' object

Here are the routes in my application: const routes:Routes =[ {path:'', component:WelcomeComponent}, {path:'profile', component: ProfileComponent}, {path:'addcourse', component: AddcourseComponent}, {path:'course ...

Iterate through a directory on the local machine and generate elements dynamically

I am looking to create a jQuery-UI tabs menu that includes 54 images on each tab. I have a total of 880 images stored in a folder, and it would be very time-consuming to manually insert an <img> tag for each one. Is there a way to dynamically cycle t ...

Using Slick.JS to Sync Navigation with Main Slider, Automatically Resetting to First Slide

I have a question about the functionality of the Slick.JS plugin that I'm using. In my project, I have two carousels with five slides each. The top carousel displays one slide at a time, while the bottom carousel shows all five slides concurrently. My ...

Reveal hidden elements once the form has been submitted

At this moment, the info, stat and foo elements are hidden. Strangely, when I submit the form, they don't become visible. However, if I incorporate the unhide() function within the <button onclick="unhide()"></button>, it works p ...

Using AngularJS to bind objects with a checkbox

I am dealing with a nested list of objects that can go up to three levels deep. Each object contains another nested object, and this nesting can continue to multiple levels. I am interested in binding these objects directly to checkboxes so that when I che ...

Can a PHP script be executed through an Ajax event?

Is it feasible to execute the script of a PHP file when an AJAX event is triggered? Consider this scenario: on the AJAX error, could we send the data to the error.php file, record the error, notify the admin via email, and perform any other desired action ...

Switching out the background image with a higher resolution one specifically for users with retina devices

I'm trying to create my very first website that is retina ready, but I've run into an issue when it comes to updating images to higher resolutions in CSS. I'm unsure how to go about having a standard image as the background and then switchin ...