Send a Dictionary<String, List<String>> object to JavaScript

I am looking to send a Dictionary> from the server to the client using JavaScript.

Although I came across this post, I am still unsure about the steps to follow. To clarify my objective, the dictionary comprises the 'name' key of all worksheets in an Excel file, with the 'value' representing the column value of the first row in each worksheet. The user interface on the client side should include two drop-down lists: one containing the names of all worksheets in the Excel file (keys), and the other displaying the column values of the first row of the selected worksheets (values).

The C# backend code is functioning correctly. Right now, I require assistance with the frontend JavaScript implementation.

How can I structure the data as key-value pairs in order to perform a "search" based on the keys chosen by the client? Once a key is selected from the first drop-down list, I need to retrieve the corresponding values in a list format.

Thank you!

   var ajaxRequest = $.ajax({
        type: "POST",
        url: "http://localhost:1894/api/Values",
        contentType: false,
        processData: false,
        data: data,
        success: function(dataTest) {

        }
    });

Here is the JSON response received from the server:

{"First":["Name","Link","User","Pass"],"Sec":["test01"]}

In JavaScript, how can I search through this data similar to C#? I aim to achieve something like "dict.TryGetValue(key, out value);" where the value returned is an array of strings or a List.

Answer №1

If you don't want to use the var ajaxRequest variable, you can call the function directly like this:

 $.ajax({
    type: "POST",
    url: "http://localhost:1894/api/Values",
    dataType: "json",
    data: data,
    success: function(dataTest) {
        //dataTest should contain your data in a javascript object
        for(var i = 0; i < dataTest.First.length; i++)
        {
            window.alert("" + dataTest.First[i]);
        }
        for(var i = 0; i < dataTest.Sec.length; i++)
        {
            window.alert("" + dataTest.Sec[i]);
        }
        //etc...
        //this should print the values returned if you showed me exactly how your JSON is...
    }
 });

The object will have properties with an array as the value for each property. It's similar to a map of strings to string arrays. So your object dataTest will have properties First and Sec. For example, the value associated with key First will be ["Name","Link","User","Pass"], which is an array. Same goes for Sec. Therefore, dataTest.First[0] equals "Name", dataTest.First[1] equals "Link", and so on.

*****************************************UPDATE**************************************

You can save your dataTest to a global variable (e.g., myObject) then access it as follows:

var key = "First";
// If you want to get the key from a dropdown (select) element, you could do this:
var key = document.getElementById("myselect").options[document.getElementById("myselect").selectedIndex].innerHTML;

if(myObject[key] != undefined)
{
    //There are values for this key.
    //Loop through values or manipulate myObject[key] as needed.
    for(var i = 0; i < myObject[key].length; i++)
    {
        window.alert("" + myObject[key][i]);
    }
}

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

What is the best way to pass variables between nested directives?

When a directive called el2 is nested within another directive called el1, I face challenges in accessing variables that are "locally declared" in el1 (such as variables generated by ng-repeat, ng-init, etc) from el2. For a practical example showcasing th ...

Change the height of a div after submitting a form using Django (Python)

I have a registration form with one submit button. Upon clicking submit, if there is an error, the height of the div increases by setting it to height:auto. However, when I click submit, it changes the height of the div (.continer). Strangely, after one ...

Unable to locate module post npm installation

My Node.js application is running on an Ubuntu server hosted on Microsoft Azure. The package.json file for my project includes various dependencies required for the app to function. { "author" : "Coop", "name" : "app-framework", "main" ...

What sets apart using 'self.fn.apply(self, message)' from 'self.fn(message)', and what are the advantages of using the former method?

Whenever I come across code that looks like thisnewPromise.promiseDispatch.apply(newPromise, message), I can't help but wonder why they didn't simply use newPromise.promiseDispathch(message) ...

Troubleshoot: Unable to utilize mapActions with Vuex modules

Having trouble using mapActions to reference actions in my modules. The Vuex docs say that module actions are not namespaced by default, so they should be accessible like main store actions. Here's how I have things set up: Store import * as ModuleA ...

Issue with ReactJS: onChange event does not function properly when value is changed using jQuery

This is the reactjs code I am working with: <input name="date" id="date" value={this.state.listManage.date} onChange={this.handleForm} type="text" /> When I manually type in the input field, the onChange function works ...

Filtering data at different levels in Javascript/Javascript programming language

Consider this array: var selection = ["14-3","19-5", "23-5", "40-8", "41-8"]; We now have two separate arrays: Array1 includes the first part of each value (before hyphens) in the original array, such as 1 ...

Creating a user-friendly interface for the admin to easily upload photos by implementing a php/bootstrap/js code within the panel

I'm currently in the process of creating an online website as part of my thesis project. I've been researching this specific code, but unfortunately, I haven't been able to find a solution. In the admin section of the site, I need to enable ...

Angular 2: Change Boolean value depending on a condition

I find myself facing a challenge with a search-bar feature. My goal is to display all the filtered names when the input value reaches a length of 2 or more characters. After successfully extracting the value.length from the input field, I encountered a ro ...

Navigate the Angular interceptor route to display a 404 error page when clicking on a `<a href="#">` tag

When using href="#" as a placeholder in html, I encountered an issue where Angular was unable to recognize it and would route to the 404 page despite having the following configuration in the module. How can this problem be resolved? .config( function m ...

Converting a PHP array into JSON format and displaying the data on a webpage

I'm currently facing an issue with a Json Array. Here is my json data: { "res": ["000000000078", "00000001", "1367771147", "das ist mail text", "000000000080", "00000001", "1367771147", "das ist mail text", "000000000081 ...

Error message: When using the Three.JS STL Loader, an Uncaught TypeError occurs because the property 'scale' is being called on an undefined value

I am currently loading five elements using the STL Loader in order to create a table. My goal is to use dat.gui to adjust the scale of Tabletop.STL. Here is the code snippet: <!DOCTYPE html> <html lang="en> <head> <title& ...

Refreshing a React form

this.state = { name: "", arr: [], story: "" }; add(e) { e.preventDefault(); this.setState({ story: e.target.value }); this.state.arr.push(this.state.story); this.form.reset(); } <form action=""> <input onChange={this.b} type="t ...

Hero Sticky Transition with 100vhDivElement

My code is giving me some trouble. I want the div with text to stay at the bottom of the hero section with a transparent background. When that div reaches the top, it should stick with a black background. The issue is that I have set it in the javascript v ...

Having Trouble with the Back Button Functionality

Here is the code snippet I am currently using to create a "Back" button: <INPUT type="button" value="Button" onclick="window.history.back(); return true;"> The issue I am facing is that on the previous page, there are two div elements. Initially, d ...

Is it possible to verify that a string exclusively comprises elements from an array?

Hey there, I've got a challenge where I need to verify whether a string consists only of letters from a predefined alphabet. If not, my bot kicks players from the game. I've come up with the following script: var letters = "a b c d e f g ...

Having trouble accessing the session of next-auth.js within my _app.js file

I'm facing an issue where I have two providers, but I can't use both of them simultaneously. When I try to log in a user using useSession, I get an existence time error and not a user (an empty object is returned). I have a backend that returns t ...

Cease the execution of processes once a Promise has been rejected

My current code is functioning correctly, but I am facing an issue where if an error occurs, I want it to halt all other promises in the chain. Specifically, when chi.getCommand(val1, val2) returns a reject and triggers the exception catch block, I need to ...

BackboneJS struggles to redirect to .fail when an API request exceeds the timeout

I'm a newbie to backbone and I've come across some interesting code that adds Deferred to enable the use of promises. Take a look at the snippet below: getPatientInfo: function fetch(options) { var deferred = $.Deferred(); Backbone.Model.p ...

"Use ajax to implement real-time updating of website content after submitting

Is there a way to implement live updates without using setInterval or timeout functions? I've considered websockets, but I'm looking for a simpler solution. Could PHP update a key value pair file so that all pages can be updated when a specific v ...