Why is it that I cannot use the .get method on JSON data? And what is the best way to convert JSON into a map?

I'm currently in the process of creating a test for a function that accepts a map as an argument,

Under normal circumstances when the code is executed outside of a test, the parameter would appear like this (when calling toString):

Map { "id": "jobs", "label": "Jobs", "nodeType": "ROOT", "childNodesURI": "jobs?owner=*", "childIds": List [], "isFetchingChildren": false, "isToggled": true, "jobName": "" }

var node = {
                id: "jobs", 
                label: "JES Jobs", 
                nodeType: "ROOT", 
                childNodesURI: "jobs?owner=*", 
                childIds: [],
                isFetchingChildren: false, 
                isToggled: true, 
                jobName: "" };
                console.log(node.get("id"));

Upon calling node.get("id"), I encounter the error message "TypeError: node.get is not a function"

I suspect this issue arises because there is no .get() function for a JSON object, although I'm not entirely certain... If my assumption is correct, how can I convert or initialize the JSON as a map?

Answer №1

What you're displaying here is a javascript object. When referencing a "key" in this scenario, use theObject.theProperty as shown below

var node = {
  id: "jobs",
  label: "JES Jobs",
  nodeType: "ROOT",
  childNodesURI: "jobs?owner=*",
  childIds: [],
  isFetchingChildren: false,
  isToggled: true,
  jobName: ""
};

// Access the object property ID
console.log(node.id);

If you require a map, create it like this:

var myMap = new Map();

// Setting the values
myMap.set("id", "jobs");

console.log(myMap.get("id"));

If you wish to build a map based on your object, follow this approach

var node = {
  id: "jobs",
  label: "JES Jobs",
  nodeType: "ROOT",
  childNodesURI: "jobs?owner=*",
  childIds: [],
  isFetchingChildren: false,
  isToggled: true,
  jobName: ""
};

function constructMap(obj) {
    let map = new Map();
    Object.keys(obj).forEach(key => {
        map.set(key, obj[key]);
    });
    return map;
}

const map = constructMap(node);

console.log(map.get("id"));

Answer №2

To retrieve the value of `node.id`, simply use the existing code you have. There is no built-in `get()` method for object literals unless you manually add it to the prototype.

According to the documentation, a `Map` should accept an iterable object as a parameter when creating one. However, in practical usage, passing an object instead of an array can result in an error stating `undefined is not a function`. Moreover, the browser support for this feature seems incomplete (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map).

As indicated in the reference:

[1] Chrome 31 onwards, this feature was available behind a preference setting. To enable it, go to chrome://flags and activate “Enable Experimental JavaScript”.

Your two options are: either iterate over your JSON object

var m = new Map();
var json = {'foo': 'bar'};

for (var i in json) {
    m.set(i, json[i]);
}
m.get('foo');

Alternatively, if you do not require the methods provided by `Map`, you can stick with the object literal approach.

json.foo;

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

Proper Structure for Node System (BASIC)

Overview Recently, I entered the world of Node.js and built some basic back end functionality. However, I realized that everything was clustered in one file (index.js) which led me to explore tutorials on using express router middleware and adapting a mod ...

The quickest method to modify the anchor element's class depending on the query string

Requirement - I aim to accomplish this task using only pure JavaScript without any additional libraries, although I am open to using one if necessary. I need to assign an extra class to anchor elements that contain a query string of 'xyz=negate' ...

Transferring information back and forth from GWT to PHP

As someone who is new to both GWT and PHP, I have been struggling to understand how to efficiently exchange data between the frontend and backend. While I found success following tutorials that suggested using the RequestBuilder class for getting data from ...

Leveraging a JavaScript variable declared outside the function to successfully transfer data to my AJAX function

Every time the enter key is pressed, my AJAX function gets executed. I used to pass a set of javascript variables equal to elements in the HTML (the contents of a text area) as data for the AJAX function. Now, I want these JS variables to hold values from ...

Eliminating choices from a dropdown list using jQuery

I am currently working on a page that contains 5 dropdown menus, all of which have been assigned the class name 'ct'. During an onclick event, I want to remove the option with the value 'X' from each dropdown menu. My current code snipp ...

Exploring the power of ES6 map function within React stateless components

I have a React application that fetches an array of objects from an API response. I want to display each object's details in an accordion format. Using the react-accessible accordion library, I created a React Stateless Component to achieve this. Each ...

Prevent anchor link click and drag functionality on an HTML page / Swipe through a container containing links

Is there a way to prevent clicking and dragging on a link in a webpage? When you click the left mouse button on a link and drag it, you can unintentionally move the link or open a new tab. I am looking for a way to disable this behavior using JavaScript o ...

"Is it possible to include a button for horizontal scrolling in the table

I have a bootstrap table with overflowing set to auto within its container, along with a locked first column. While a horizontal scroll bar allows for viewing additional data, I am looking to incorporate buttons for navigation as well. Users should have th ...

Determine the radius using three given points

I am in need of determining the radius at the corners of a rectangle based on some given data points along the curve. The image below provides a visual representation: https://i.stack.imgur.com/7FHq0.png How can I calculate the radius using these specifi ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...

How can JavaScript transform Unicode strings?

<i class="icon">&#xe672;</i> This code will display an icon like this: > However, when I render it in Vue: <i class="icon">{{a}}</i> a = '&#xe672;' The result is  It displays as a string! ...

The convergence of Phoenix, Json, and Unix Timestamps

Currently, I am in the process of exporting data from SQL Server in json format to be able to import it into my Phoenix app. One aspect that I'm uncertain about is how to handle dates. As of now, I am exporting dates as Unix timestamps. Below is an ex ...

JavaScript - Transforming Name:ItemName/Value:ItemValue Pairs into Standard ItemName:ItemValue JSON Format

Looking to reformat JSON data? [{"name":"age","value":31}, {"name":"height (inches)","value":62}, {"name":"location","value":"Boston, MA"}, {"name":"gender","value":"male"}] If you want it to be in a different format: [{"age": 31}, {"height (inches)": 6 ...

Something is not quite right when the page is loading in a Ruby on Rails application

In the process of developing a wiki clone, I am faced with an issue involving JavaScript. When I navigate to a specific page by clicking on a link, the JavaScript does not function properly until I refresh the page. The JavaScript aspect mainly involves an ...

Has the zip creation tool in the Google Doodle on April 24th been coded entirely in JavaScript?

Was the Gideon Sundback Google doodle created using JavaScript? I attempted to follow along in Firebug, but I couldn't quite grasp its implementation details. Any ideas on how it was possibly implemented? Any insights on the potential techniques use ...

In React, the goal is to render nested data recursively and retrieve the "name" from a JSON file

How can I extract a list of "name" values from this JSON list? [ { "id": "LIB1", "name": "Library 1", "context": "C1", "children": [ { "id": "SKI1", "name": "SKill 1", ...

Reorganize items that extend beyond the list into the next column using Bootstrap

I have a row with two columns, where Column 1 currently contains 7 list items under the ul tag. However, I want to display only 5 list items in Column 1 and automatically move the remaining items to the next column (i.e., Column 2). Is there a way to ach ...

What could be preventing the fill color of my SVG from changing when I hover over it?

I am currently utilizing VueJS to design an interactive map showcasing Japan. The SVG I am using is sourced from Wikipedia. My template structure is illustrated below (The crucial classes here are the prefecture and region classes): <div> <svg ...

Changing dimensions of cube on stable base

I'm currently working on a project involving a dynamic cube that can be scaled in real time by adjusting its mesh. However, I'm facing a challenge in keeping the cube fixed to the floor while changing its height. Here's a snippet of the code ...

What is the best way to retrieve a list from a JSON file using Python?

I am facing an issue with my Python program that loads a JSON file. I need help accessing a specific list from the loaded file. Below is the code snippet responsible for loading the file: with open("database.py") as json_file: json_data = json.load(js ...