Using a variable as a parameter when requesting a value from a JSON object in JavaScript

I consider myself to be at an intermediate level in JavaScript, but I've hit a roadblock when trying to access the key in a JSON message that is returned to me.

My code is dynamic, so I need to pass the key into the query. For example:

After running this JSON query:

    var data = JSON.parse([some url]);

I receive the following formatted data:

    {
    "Status":"Success",
    "IsValidSession":"False",
    "ErrorMessage":"Success",
    "CUSTOM_MARKER_ID_FROM_DCVIEW1":
    [
        {
            "PlaceID":"CUSTOM_MARKER_ID_FROM_DCVIEW",
            "IsVisible":"true",
            "Message":"An e-stop has been pulled.",
            "ImageName":"alert.png",
            "IsPulse":"No"
        }
    ]
    }

The key "CUSTOM_MARKER_ID_FROM_DCVIEW1" needs to be variable when querying "data." I can't hard-code it like this:

    $.each(data.CUSTOM_MARKER_ID_FROM_DCVIEW1, function(i, value) {/*do some stuff*/});

Is there a way to pass in a variable after "data."?

Any assistance would be greatly appreciated. Thank you!

Answer №1

Utilize the square bracket format for better indexing:

let identifier = "SPECIFIC_ID_FROM_VIEW";
$.each(elements[identifier], function() {  ...  } );

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

Picking specific <button> items

Presented here are a series of buttons to choose from: <button id="hdfs-test" type="button" class="btn btn-default btn-lg">HDFS</button> <button id="hive-test" type="button" class="btn btn-default btn-lg">HIVE</button> <button id ...

The confusing case of jQuery's e.preventDefault: Unable to submit form despite preventing default behavior

Objective: Prevent the 'submit' button from functioning, validate fields, generate popover alerts for results, and submit form upon closing of popover. To achieve this, I have set up a hidden popover div. When the submit button is clicked, I uti ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

Grails - JSONBuilder - Specification for toPrettyString() results in a stack overflow exception

I need to create a unit test that returns JSON data. To achieve this, I am utilizing the toPrettyString() method from JSONBuilder. Here is the class under consideration: class Lugar { String sigla String nombre Coordenada coordenada String t ...

Electron's Express.js server waits for MongoDB to be ready before executing queries

As I work on a demo application, Express serves some React code that interacts with a MongoDB database hosted on mLab. The data is retrieved using SuperAgent calls in my main React code loaded via index.html. While everything works fine when starting the ...

Interpreting a JSON string with the format {TEST:[1,2,3,4]} using Gson

Can anyone assist me with parsing the following String into json format? String jsonString=" {\"TEST64\":[1,0,16,0],\"TEST59\":[2,0,17,0],\"TEST65\":[2,0,16,0],\"TEST57\":[1,0,16,0],\"TEST66\":[2,0,17,0],& ...

I am interested in running JavaScript code on a page that has been loaded through AJAX

I am struggling to execute the Javascript loaded within an ajax page. Here is the link to my loaded ajax page: https://jsfiddle.net/4dsbry7j/ JS : var xmlhttp = new XMLHttpRequest(); var url = "http://localhost/ajax/find2.php"; xmlhttp.onreadystatechang ...

Tips for using ArrayAdapter (Java) to input data into MySQL Server

As a newcomer to android development, I am looking to save call log details in a MySQL database. I have created a simple ArrayAdapter, but it is not displaying the data in the listview. Additionally, I need guidance on how to insert data into a MySQL serve ...

Group of data stored in a JSON format

I am in the process of developing a game and I am working on parsing some data for it. Here is a snippet of how the data looks: { "CircuitList": [ { "name": "GP SILVERSTONE", "location": "ENGLAND", " ...

Phantom-node failing to return the value from the page.evaluate function

My goal is to extract a specific element from a webpage and save it as an image locally. Here is the node.js code I am using with phantom-node: var phantom = require('phantom'); phantom.create().then(function(ph) { ph.createPage().then(funct ...

The discord.js TypeScript is throwing an error stating that the 'index.ts' file is missing when trying to run 'ts-node index.ts'

I have been working on creating a discord bot using discord.js and TypeScript. However, when I attempt to start the bot by running 'ts-node index.ts', I encounter the following error: Error: Cannot find module 'node:events' Require stac ...

Steps for sending an HttpClient request in C# to retrieve the output from the following code

I am currently running a webservice where I can use Swagger to get the result file from an API controller. However, I am facing difficulty in making the call from my console application to retrieve the results. What would a HttpClient call look like in C# ...

Woocommerce API encountered Error 100 due to an Invalid JSON Response

Utilizing the woocommerce V2 product api to automatically load product information has been successful, but there are instances where an "Invalid JSON Returned" error with code "100" occurs, even when the calls are identical. This issue is intermittent an ...

What is the reason behind being able to use any prop name in a React function without explicitly mentioning it?

Currently, I'm delving into the world of mobX-state-tree, and in the tutorial code that I'm exploring, there is an interesting piece that caught my eye. const App = observer(props => ( <div> <button onClick={e => props.store. ...

Enhancing server error troubleshooting with Next.js: improved stack trace visibility?

When a server error happens on Next.js, the call stack only provides information about the specific component where the error is located without offering any further guidance. For instance, in /pages/index.js, I have a component named Test. Within this co ...

The particular division is failing to display in its designated location

This is quite an interesting predicament I am facing! Currently, I am in the process of coding a website and incorporating the three.js flocking birds animation on a specific div labeled 'canvas-div'. My intention is to have this animation displa ...

Node functions continue to run smoothly without affecting the loop

I am working on a webdriverjs application and I am trying to determine when jQuery has finished its processes on the page. I have implemented some methods, but it seems that even when the condition is supposed to trigger an else statement and stop the loop ...

Crafting dynamic objects with THREE.JS

I am working with a JSON configuration that looks like this: { shape:[ 'SphereGeometry', [7, 16, 16] ] } My goal is to load a model using the following code: new THREE[shape[0]].apply( this, shape[1] ) However, it seems that using "new" and " ...

The transition between backgrounds is malfunctioning

I want to create a smooth transition effect for changing the background of an element within a setInterval function. Currently, the background changes immediately, but I would like it to transition over a period of time. var act = true; setInterval(func ...

Effectively implementing an event observer for dynamically loaded content

I want to set up an event listener that triggers when any of the Bootstrap 3 accordions within or potentially within "#myDiv" are activated. This snippet works: $('#myDiv').on('shown.bs.collapse', function () { //code here }); Howeve ...