Manipulating JSON data by accessing and updating a specific property with the help of a variable

Let's dive into the complexities of my current project. I am delving deep into U.S. Census bureau information, specifically focusing on a snippet of data from an object that looks like this: (Remember, this is only a portion of the complete object.)

Object {MTFCC: "G5020", OID: 207903717468543, GEOID: "13135050431", STATE:     
"13", COUNTY: "135"…}
AREALAND: 5416158
AREAWATER: 34463
B19013_001E: "45543"

The key element capturing my interest is B19013_001E, denoting the code for Median Household Income. To pinpoint the exact Median household income figure, I would use:

response.features[1].properties.B19013_001E

All seems to be functioning smoothly so far. However, here lies my dilemma: I aim to interchange that code with other values. For instance, if someone wishes to inquire about median_male_age, represented by the code B01002_002E, I want to steer clear of hard-coding in B01002_002E as follows:

response.features[1].properties.B01002_002E

This method would indeed yield results. Yet, I desire a more dynamic approach that hinges on a variable rather than statically inputting the particular code. Thus, envision a setup akin to this hypothetical scenario:

var value = prompt("What do you want to look at: ")
//Here, 'value' would assume the special code inputted by the user, such as B01002_002E.
console.log(response.features[1].properties.value)

Regrettably, all my attempts in this direction have been met with silence. Initially, I suspected a mismatched data type, but upon deliberation, I don't think that's the root cause (I experimented with number conversion and string manipulation). Any insights on resolving this conundrum would be immensely appreciated!

Answer №1

Adding on to my previous response.

To delve deeper into this topic, check out the comprehensive documentation on Working with objects provided by MDN.

It's essential to understand that JSON is actually a string and not an object, which is why it stands for JavaScript Object Notation. What you possess is commonly known as a POJO, or Plain Old Javascript Object. These distinctions are important! :)

When addressing your specific query, make sure to utilize bracket notation when accessing an object property through a variable. In this instance, the correct syntax would be:

console.log(response.features[1].properties[value])

I hope this explanation clarifies things for you!

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

Update the src attribute in an HTML document

I am looking to dynamically change the size of an image on an HTML page using a dropdown list. Here is my code: <html> <head> </head> <body> <select id="selectbox" name=""> <opti ...

Having difficulty accessing the key values from an Object

This piece of code utilizes Axios to fetch data and store it in the myObject variable: const myObject = {} Object.entries(keysParameter).map((entry, index) => { axios .get(url) .then((res) => { myObject[entry[1].value] = re ...

Utilize the forEach filter method to display the database based on the specific id

I'm trying to display a specific meal by its ID and also show the reviews for that meal. The issue I'm facing is that when rendering a review, it always displays based on the same ID. For example, if a user clicks on a menu with an ID of 2, then ...

Is it possible to trigger a JavaScript function by manipulating the URL of an HTML page?

Imagine this scenario: You have an HTML page located at example.com/test.html that contains several pre-defined JavaScript functions, including one named play(). How can I add JavaScript to the URL in order to automatically trigger the play() function wh ...

Is there a way to stylize the initial words of a brief text block by blending small caps with italics, all while avoiding the use of a span tag?

I have a series of images with numbered captions like "Fig. 1", "Fig. 2", "Fig. 3", followed by a brief description on the same line. Is there a way to programmatically style these strings (the “Fig. #” only) using CSS or Javascript to make them italic ...

Using JavaScript, access Google API to retrieve reviews for my business

I've been struggling to generate Google reviews for my business and I'm having difficulty implementing it. Can anyone provide guidance on how to retrieve the latest/top 5 reviews using the Google Business API with JavaScript/Postman? Here is what ...

Understanding how to parse JSON data with jQuery in a multidimensional

Here is a JSON array example: { "etablissement": { "siege_social": true, "siret": "41816609600051", "naf": "6202A", "libelle_naf": "Conseil en systèmes et logiciels informatiques", "etat_administratif_etabliss ...

Tracking modifications in a text document using ajax (javascript)

After conducting extensive research, I have yet to find a solution that addresses the issue at hand. My current webpage features a text input field that triggers a function whenever its contents are changed, resulting in data being written to a text file. ...

Is it possible to prevent a postback by utilizing JavaScript's confirm function?

I am currently working on an aspx page that contains an asp.net button. The code for the button is shown below: <asp:LinkButton ID="btn_Delete" runat="server" OnClick="btn_Delete_Click" OnClientClick="ConfirmDelete();" Text="Delete" /> The Confirm ...

Updating a JSON file locally within an Angular application

I am facing a challenge with modifying a json file. Although I have successfully mapped it into a model, the issue lies in saving or overwriting the existing json file. Despite trying to use file-saver, I realized that changing the save directory is not po ...

Dynamic filtering with Javascript

I am searching for inspiration on how to create a filter in the left sidebar that dynamically updates the page content when clicked, and if there are subcategories, displays them below the selected filter in the sidebar. I've discovered that AJAX is ...

The Json parsing failed to deserialize the API response

Struggling to send a JSON to my API, I've tried various solutions but still can't figure out what's going wrong. I'm stuck on this post call function: @PostMapping(path = "ts/sts") public void saveTestStep(@RequestBody Tes ...

How can I ensure that Bootstrap Navbar elements are all aligned in a single line?

https://i.sstatic.net/pkxyI.pngI'm experiencing an issue with my code, and I suspect it might be related to Bootstrap. I've tried using align-items-center but it doesn't seem to work as expected. Changing the display property to inline or in ...

ajax is not sending the data to be processed by php

As a newbie to ajax, I have been attempting to submit data for processing and insertion into the database using PHP. Unfortunately, it has not been successful so far and I am unsure of the reasons behind this issue. Here are the steps I've taken up to ...

Ruby on Rails and JSON: Increment a counter with a button press

How can I update a count on my view without refreshing the page when a button is clicked? application.js $(document).on('ajax:success', '.follow-btn-show', function(e){ let data = e.detail[0]; let $el = $(this); let method = this ...

How can we display or conceal text indicating the age of a patient based on the value returned from selectedPatient.age in a React application?

Hello, I am looking to dynamically display the age in years on the screen based on the value retrieved from selectedPatient.age, toggling between visible and hidden states. import React, { useContext } from 'react'; import { useHistory } from &ap ...

Ways to resolve the issue of "await not waiting"

When I run an asynchronous function, I prefer to use the await declaration outside of the "then" method like this: const todayTotalVisitor = await getLastDayVisitors(); This way, the await keyword does not wait. async function calculateMonthTotal() { c ...

How to use Javascript to fetch HTML content from an external website

Is it possible to access and retrieve scores from for a specific week using AJAX or JSON technology? Each game on the website seems to have a unique class which could make retrieving score information easier. Any guidance or assistance would be greatly ap ...

Looking to transfer a cell value to different cells within an HTML table

Currently, I am utilizing a basic HTML code to duplicate the value from the first cell to all other cells. You can take a look at how the HTML table appears here. In addition, I am attempting to automatically fill in the remaining dates once input is provi ...

What is the solution for the 'document is not defined' error occurring in an EJS file when utilizing res.render() in Node.js?

I need to send this specific ejs file as a response using res.render() in my node.js application <!DOCTYPE html> <html> <head> <title>pilcit</title> </head> <body> <% var btn = document.getElementById(&apos ...