Extracting values from a JSON object in JavaScript

Is there a way to retrieve the _id and state values from the provided data?

Check out the data

{
    "data": {
        "totalSamplesTested": "578841",
        "totalConfirmedCases": 61307,
        "totalActiveCases": 3627,
        "discharged": 56557,
        "death": 1123,
        "states": [
            {
                "state": "Lagos",
                "_id": "O3F8Nr2qg",
                "confirmedCases": 20555,
                "casesOnAdmission": 934,
                "discharged": 19414,
                "death": 207
            },
            {
                "state": "FCT",
                "_id": "QFlGp4md3y",
                "confirmedCases": 5910,
                "casesOnAdmission": 542,
                "discharged": 5289,
                "death": 79
            }
        ]
    }
}

Answer №1

The JSON format you presented can be easily converted into a JavaScript object. Once converted, you can access and retrieve the necessary values from it.

let jsonString = ‘{
    "data": {
        "totalSamplesTested": "578841",
        "totalConfirmedCases": 61307,
        "totalActiveCases": 3627,
        "discharged": 56557,
        "death": 1123,
        "states": [
            {
                "state": "Lagos",
                "_id": "O3F8Nr2qg",
                "confirmedCases": 20555,
                "casesOnAdmission": 934,
                "discharged": 19414,
                "death": 207
            },
            {
                "state": "FCT",
                "_id": "QFlGp4md3y",
                "confirmedCases": 5910,
                "casesOnAdmission": 542,
                "discharged": 5289,
                "death": 79
            }
        ]
    }
} ‘;

(Please note: the string is in single quotes here for proper display, but it should be in back ticks in your code to span multiple lines)

To convert the string to a JavaScript object, use:

let jsonObject = JSON.parse(jsonString);

Upon examining the structure of the object, you'll see that it contains a single item called data, which is an object with various attributes including an array called states.

Therefore, accessing obj.data.states[0] will give you the first entry of the array, which includes items like _id and state.

You can iterate through the array to extract the _id and state values as needed.

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 rate a particular image?

while ($row = mysqli_fetch_array($result)) { echo ""; echo "<div id='img_div'>"; echo "<i class='fas fa-times'></i>"; echo "<img class='photoDeGallery' s ...

How can I ensure that VueJS only starts loading data after the initial API call has been completed?

After retrieving data from an API, I populate a form in my component. The challenge I am facing is that the watchers are triggered immediately after populating the initial data. I want them to be triggered asynchronously. Additionally, I need to prevent th ...

Unable to upload gathered email to Mailchimp mailing list through Nodejs and express API

Seeking guidance on integrating data collection with Mailchimp in a Nodejs backend project. I am currently working on an email signup list page where users input their first name, last name, and email. The HTML file contains fields named firstName, lastN ...

What is the best way to retrieve the local image path, transform it into a File object, and subsequently transfer it to firebase?

My current form includes a signup option where users can choose to upload a profile picture. In case they do not upload a profile picture, I aim to use a default one (think of the default Facebook profile picture). The image is imported as: import defaul ...

Extract data from a DataFrame column using Spark Scala and convert it into an RDD with multiple columns

In my SparkScala RDD, the structure looks like this : df.printSchema() |-- stock._id: string (nullable = true) |-- stock.value: string (nullable = true) The second column of the RDD contains nested JSON data: [ { "warehouse" : "Type1" , "amount" : "0 ...

Updating an array nested within an item of my state array using Angular 2 ngrx

Within my reducer function, I am looking to include an element that is nested within an array, following this JSON structure received via http services: JSON structure: { "id": "09fabf9a-e532-4d2a-87cc-bd949a0a437f", "title" ...

Display an array using the MsgBox function in VBA

I'm not very experienced with VBA, but I'm looking to verify some values and could use some assistance. My goal is to create and display an array using the MsgBox function. The array is generated and populated within a for loop that performs cal ...

Converting a struct to an array format without keys using serialization and deserialization

Is there a way to serialize and deserialize a struct without specifying keys? By using indexes as keys, the order of fields can be preserved which would result in a smaller payload size. I am currently utilizing serde_json and ciborium crates, both of whi ...

BlendModeGlobal operations

Experimenting with the globalCompositeOperation property in a loop by passing different strings (source-atop, source-over, etc.) to the same 2D context, I observed that Firefox only allowed me to draw a few shapes while Opera only displayed the last one. ...

What could be causing the issue with my connection.query when using mysql in node.js?

Purpose: The goal is to perform a basic query on the database. Expected Outcome: The console should display "please print something!" along with the results of the query. Actual Outcome: Sadly, nothing appears on the terminal screen. Issues: No error me ...

Close to completing the AngularJS filter using an array of strings

I'm currently working on developing a customized angular filter that will be based on an array of strings. For instance: $scope.idArray = ['1195986','1195987','1195988'] The data that I aim to filter is structured as fo ...

What is the ideal format for an AJAX request that includes sections for handling success and error scenarios?

When making AJAX calls for CRUD operations in MVC, I often find myself unsure about the standard or most common usage of the complete, success, and error functions. Some examples show these functions without any parameters, while others include parameter ...

Using jQuery to add the name of a file to FormData and fetching it in a PHP script

I've been working on a JS code snippet dedicated to uploading images based on their file paths: var data = new FormData(); data.append('fileName', fileName); data.append('file', file); $.ajax({ url : dbPath + "upload-file.php" ...

What is the best way to set multiple headers and change the content type when needed?

I am struggling with a function that cannot be overridden: getHtml:function(aURL,aPostData,aHeaders,aMethod){ this.xhr = new XMLHttpRequest(); var tmp=this; this.xhr.onreadystatechange=function(){ tmp.onStateChange(); }; if(aPo ...

Ways to showcase the contents of a React JavaScript document, or more specifically, a file designed for React interpretation

After trying multiple solutions, I found a conceptual guide on How to call and form a React.js function from HTML. However, the HTML generated doesn't seem to be calling from the JavaScript file as expected. It appears identical to what is mentioned i ...

Issue arises while utilizing the echoed ++$value in javascript within a webpage containing an HTML5 audio player

I've been developing a customized 'soundboard' that generates a unique HTML5 audio player for each mp3 file found in a directory. While the player setup is functioning as expected, I encountered challenges when incorporating a customized tim ...

Vue.js known as javascript hooks

I've been working on connecting Vue.js with velocity.js. Following a guide, I found an example that doesn't use a named transition. Currently, my transition code looks like this: <transition name="collapse"> https://v2.vuejs.org/ ...

How to parse static properties with json.net?

Hey everyone, I've got a JSON structure like the one shown below: { "totals": { "tokenType": "string", "tokenDenomination": "double", "count": "int" }, "IDCode": "string", "Key": "string" } And here is the C# code to deserialize ...

Troubleshooting problems with bot roles on Discord

After spending some time coding my bot, I encountered an issue when trying to add a role to a user who didn't already have it. Everything seemed to be functioning properly until I included the member.roles.add command. Despite having every possible p ...

Select2 loading screen featuring preloaded value

Trying to populate a select2 box with instrument options on an edit profile page for a musician site. The information is pulled from the database, but I'm struggling to display the existing instrument list in the select2 box upon render - it always ap ...