Converting a 2D JSON string array into JavaScript objects

Hey there! I'm currently dealing with a JSON string that has the following structure:

{"2000":["1", "2", "3"],"2001":["1", "2", "3"],"2002":["1", "2", "3"]}

This JSON string is coming from the backend, and my JavaScript function receives it as a parameter named backendData.

When trying to loop through this parameter using the code snippet below, I get the following output:

for (key in backendData) {
    alert(key);
}

This will result in three separate alert boxes displaying: 2000, 2001, and 2002.

The issue I'm facing is figuring out how to access the string array associated with each of these "parent" elements. Simply using syntax like key[0] gives me the character at index 0 of the string, which in all cases is "2".

If anyone has any suggestions or solutions, your help would be greatly appreciated!

Thanks in advance,

/Michael

Answer №1

Looping through all the values is essential here. Keep in mind that backendData is simply a JavaScript object.

for (key in backendData) {
   for (x in backendData[key])
    alert(backendData[key][x]);
}

In the case of your specific data, this method would be effective:

for (key in backendData) {
   alert(backendData[key][0];
   alert(backendData[key][1];
   alert(backendData[key][2];
}

Answer №2

It seems like what you're looking for is:

backendData[key]

This will allow you to search for a mapping within the backendData map. Using key[0] will only access an element inside of key (assuming it's a character array), which is not what you intended to do.

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

Error: The function "this.state.data.map" is not defined in ReactJS

class Home extends Component { constructor(props) { super(props); this.state = { data: [], isLoaded: false, }; } componentDidMount() { fetch("https://reqres.in/api/users?page=2") .then((res) => res.json ...

personalized XMLHttpRequest method open

var open = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) { this.addEventListener("readystatechange", function(event) { if(this.readyState == 4){ var self = this; var respons ...

Next.js Firebase Analytics Error: Undefined Window Object

I am currently working on implementing and exporting the Firebase analytics module in Next.js using Firebase v9. When attempting to run the code snippet below, I encountered an error message stating "ReferenceError: window is not defined". Howev ...

Detach an item from its parent once it has been added to an array

Currently, I am facing an issue with a form on my blog. The blog is represented as an object that contains multiple content objects within it. I seem to be experiencing some confusion because the reactivity of the content I add to the Array persists with t ...

Observing a two-way binding in AngularJS directive with the $watch functionality

I am currently working on differentiating between internal changes and external changes using a two-way data-bound attribute ('='). To clarify: I want to prevent $watch from triggering if the change was made internally (such as altering the scop ...

The property being set in Angular is undefined, causing an error

I am struggling to understand why the code below is not functioning as intended: Main.html <div class="MainCtrl"> <h1>{{message.test}}</h1> </div> Main.js angular.module('myApp') .controller('MainCtrl', f ...

How can I ensure the screen is cleared before the next frame in three.js?

While working in Three.js WebGLRenderer, I understand that using context.clearRect() requires a canvas and other elements. However, my question is: How can I achieve the same functionality as clearRect in Three.js WebGLRenderer? In my game, a JSON model i ...

Is there a potential problem with unescaped characters in an HTML field within a JSON response?

Imagine an API returns a JSON response as shown below: {"error":"","data":"example_html_code_here"} Instead of showing "example_html_code_here", the actual HTML code or page is returned. Should this HTML code be es ...

Generating JSON data with nested structure in Oracle SQL

I am struggling to generate a nested JSON object in Oracle SQL. While I have successfully created JSON objects with predefined hierarchy levels, the challenge lies in creating a dynamic nested structure using SQL or PLSQL. Below is the data from my table: ...

Error: Unable to import 'index.js' with the require() function in the current directory

A directory named src/config contains multiple files: a.js, b.js, c.js, and index.js While working within b.js, I encounter the issue where const data = require('./index'); OR const data = require('./index.js'); always results in ...

JSON error in Xcode causing exceptions

As a beginner in iOS, I am working on developing a function that uses JSON to access data and then insert it into a UITableView. However, I am encountering an error at this section of my code: NSDictionary * dict = [[CJSONDeserializer deserializer ] ...

Utilize service codes from one application within another App in Angular 8

Can a singleton service be created within a "common-components" app and then accessed by another angular application? This service would handle CRUD operations that are used across all applications. We are managing five Angular 8 applications in a microse ...

Is there a way to incorporate an MTN Momo or Orange Money payment system into your application if you are not a registered business entity?

Implementing an MTN Momo and Orange Money payment system through their respective APIs is crucial. In addition, I am seeking a dependable and effective method to seamlessly integrate these diverse APIs. During my attempt to incorporate the API via their ...

main.js:1 ERROR TypeError: Unable to access property 'querySelectorAll' of null

I am currently using Chartist in conjunction with Angular to generate charts. However, I am encountering a problem where the charts do not display when the server is running, and an error appears on the console. Strangely enough, refreshing the page caus ...

Creating a React Mui TextField specifically for currency input on iPhone Safari: ensuring that only digits are allowed

I have implemented a Mui TextField component for currency input that displays only the numeric keyboard in the Safari browser. However, I want to restrict users from pasting literal strings into the field and ensure that only currency number inputs are al ...

Enhancing user experience by tailoring rewrites in Next.js according to the user-agent

I am working on a NextJs multi-domain website and need to fetch data based on the domain and device type. While I am able to identify the domain, I am looking to extract the user-agent in rewrite rules and utilize it within the getStaticProps function. Bel ...

Online Adventure - Saving Conversations

I am interested in developing an RPG using JavaScript. The game will involve a significant amount of dialog. While I have knowledge of PHP and MySQL, I am new to XML. My queries are: Would it be more efficient to store the dialog in a MySQL database and ...

The challenge of navigating through $scope

In my Angular view/form, I have an input file element that is being utilized with ng-upload. The code snippet looks like this: <input id="img" type="file" name="image" onchange="angular.element(this).scope().setFile(this)"> <input id="imgname" ty ...

"Utilizing the power of Twitter Bootstrap and Snap.js for

I am currently working on integrating Snap.js by jakiestfu with Twitter Bootstrap. I have managed to make it work to some extent (I can slide the content and open a drawer through a click event). However, I am facing a challenge where the drawer content re ...

Using JavaScript to replace a radio button with the term "selected"

I am currently in the process of developing a quiz that is powered by jQuery and possibly JSON, with data being stored in a database. Everything is functioning correctly at this point, but I would like to enhance the user interface by hiding the radio butt ...