Having difficulty executing a loop on the JSON response object

I've stored categories and their types in a dictionary in a .cs file, like this:

Dictionary<string, List<string>> jsonDic

To convert it into a JSON object string, I used the following logic:

JavaScriptSerializer jss = new JavaScriptSerializer();
string barJson = jss.Serialize(jsonDic);
string js = "TypesArray(" + barJson + ")";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Startup1", js, true);

In my .js file, I'm receiving the following response:

The result is not in array form, so I can't index points as it's not an array. How should I proceed? I need to be able to index both categories and types associated with each category.

Answer №1

To retrieve any of the attributes, simply refer to them by name.

 tpoints["Foods"]

This will give you an array of strings related to foods:

[Restaurant, Cafe, Bakery]

If you need to loop through the attributes:

for (var property in tpoints ) {
    if (tpoints.hasOwnProperty(property)) {
        // perform actions
    }
}

Answer №2

It seems there may be a bit of confusion regarding the data structure you are dealing with. The title of your question is misleading...

Having trouble executing a for loop on a json response object

because you are actually able to iterate through the json objects. When you serialize the object shown below...

Dictionary<string, List<string>> jsonDic;

the serializer is effectively converting each KeyValuePair object within the dictionary into a json array item, known as tPoint. To loop through this array, all you need to do is...

for (var tpoint in tpoints ) {
    tpoint.Foods; //get food array
    tpoint.Foods[0]; //retrieve first food item

}

You can even include a nested for loop to iterate through each inner array like so...

for (var tpoint in tpoints ) {

    for(var i = 0; i < tpoint.Foods.length;i++){
        console.log(tpoint.Foods[i]);
    }
}

This will cycle through all food items in every tpoints

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

Understanding the res.render method in JavaScript can be a bit tricky at first

In my spare time, I have been immersing myself in coding lessons and have encountered some puzzling aspects of the code: Firstly, there is a confusion surrounding the action attribute in HTML Secondly, this particular piece of code is causing me some b ...

Using a three.js texture with a JSON object

Currently, I am working on a customization project where I am using three.js to export an HTML5 canvas as a 3D preview. My goal is to have the texture placed only on the front side, but it seems to appear on all sides instead. This is the code I am using: ...

Array logging mistakenly outputs a number

I needed to access the data from JSON outside of the xml function so that I could use it in multiple functions. When I initially logged the data, it displayed arrays with objects in it. However, when I checked the length instead, it returned zero. After re ...

The json.stringify method is inserting additional backslashes into the response sent by res.send()

My API needs to provide the following data in its response. { users: 'All users are as follows: [{id: 1}, {id: 2}]'} The response should be a JSON object with one key value being a JSON array. However, the JSON array is converted into a string b ...

Discovering all routes and categories of a JSON using System.Text.Json in .NET 6

I've created a method to retrieve all combinations of Path + Type for every key in a JSON using the JSON.NET library: public static IEnumerable<string> GetKeys(this JToken jToken) { var keys = new List<string>(); var jTokenKey = $ ...

Is it possible to create a webpage where the header and footer remain static, while the content in the body can be dynamically changed

I am in the process of creating a webpage where main.html will load a page with a static header and footer that remains unchanged when navigation links are clicked. I'd like to achieve this using Javascript, with the body content being sourced from an ...

Unable to show PHP results in HTML

I've tried many solutions from different articles, but none seem to work for me. I would greatly appreciate any assistance in displaying the Full_Name field within an HTML element on my webpage. Below is the content of the PHP file: {"Test_Info": { ...

Swapping out meshes on the fly using three.js動态替换单个网格与

I have a unique idea for a breakout game where the paddle is shaped like a piece of roof trim, with its shape changing based on the pitch of the roof. Hitting special bricks will alter the pitch variable, thus changing the "steepness" of the paddle. Howeve ...

React & Material UI: Unleashing the Power of Chained Arrow Functions

I stumbled upon this code snippet while browsing through the Material UI docs on Accordion. Despite spending hours trying to understand it, I'm still struggling to grasp its functionality: export default function CustomizedAccordions() { const [expa ...

Unveiling the secrets of delivering Nested TreeView JSON through Web API

Hello, I am new to working with web APIs and I could really use some assistance in generating a JSON structure that looks like the example below: [ { 'id': 66, 'text': 'This is the first comment.', ...

What is the best method for finding and observing the Javascript code being utilized on a webpage?

Is there a way to find and access specific Javascript used on a webpage? Imagine browsing through a webpage's source code and stumbling upon an element like this: <img border="0" alt="" onmouseout="hidetrail();" onmouseover="showtrail('imag ...

The issue of Ejs partial header and footer file only functioning in one file and not the other (both at the same directory level)

I'm in the process of setting up a view page for a post on the main page of a website. Both pages share the same header and footer files, located at the same directory level. However, while one page is functioning correctly, the other is not. The erro ...

The PHP sorted array loses its order when encoded into JSON and then sorted in JavaScript

In my PHP code, I have two arrays that I need to work with. The first array is sorted using the arsort() function like this: arsort($array1); After sorting, I output the contents of both arrays like so: foreach ($array1 as $key => $val) { $output ...

Looping through jQuery click() function

I used a loop to generate div elements and I am trying to modify the background-color when the div is clicked. var c = $("#container")[0]; for(var i=0; i<6; i++){ var x = document.createElement("div"); x.className = "sqare"; x.click(changecolor(t ...

Guide on linking Influxdb information in a Vue application using node.js?

I have successfully connected my InfluxDB database to my Vue app and can log data in the terminal using the code below: // index.js import express from "express"; // These lines make "require" available import { createRequire ...

worldpay implements the useTemplateForm callback function

My experience with implementing worldpay on my one-page Angular app (Angular 1.x) has been mostly positive. I have been using the useTemplateForm() method to generate a credit card form and retrieve a token successfully. However, I have encountered an issu ...

Implementing validation for a Textbox based on changes in another component's value in React.js

Is it possible to trigger validation of a Textbox based on the value change of another custom component that updates the state? Handlers: handleValueChange = (val, elementName) => { this.setState({ ...this.state, [elementName]: val ...

Leverage Async/Await in React.js with the Axios Library

Recently, I came across an interesting article on Medium titled How to use async/await with axios in react The article discussed making a simple GET request to a server using Async/Await in a React.js App. The server returned a JSON object at /data with t ...

create the text with double bold - adjusted pages

Is there a method to enhance the boldness of the text without adjusting the font size? Currently, the following styling is applied: numbers: { fontSize: 30, color: '#31C283', fontWeight: 'bold', }, Is there a way to m ...

Trying to understand the strange behavior of HTML parsing with jQuery in Javascript and Firefox

I have been working on a script to parse an HTML page using jQuery. The script runs smoothly in Chrome, IE, and Safari, but I'm facing some unexpected behavior while testing it in Firefox (version 36.0.1). Here's the code snippet: $.ajax({ u ...