Fetching an attribute from an array using a URL parameter in JavaScript

I am attempting to filter a JSON array based on a value from a URL and extract the vernacularName attribute. While debugging in F12, I can successfully retrieve the correct variable using record[0].vernacularName;, however, the code below still does not work.

document.getElementById("demo").innerHTML = datasetID;
functions as expected, but
document.getElementById("demo").innerHTML = vernacularName;
does not.

My end goal is to store the vernacularName as a session variable.

<body>
  <div class="">
    <h3>testing data</h3>
    <p id="demo" class = 'pl-5'></p>    
  </div>



<script type="text/javascript">
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);

  const species = urlParams.get('species')
  const bone = urlParams.get('bone')

  const datasetID = urlParams.get('datasetID')

  var data;
  $.getJSON("json/data.json", function(json){
    data = json;
  });

  record = data.filter(r => r.datasetID == datasetID);


  var vernacularName = record[0].vernacularName;
  // const vernacularName2 = record.vernacularName;
  $_SESSION["v"] = vernacularName;


</script>

<script>
document.getElementById("demo").innerHTML = vernacularName;
</script>

Answer №1

Initially, I am uncertain as to why

document.getElementById("demo").innerHTML = vernacularName;

it is enclosed in its own script tag. It appears quite unusual.

Regardless, the issue at hand is that the data is not yet available. You cannot begin processing the data and updating elements on the page until the data has been retrieved.

This is where the second argument of getJSON comes into play - it is a function that is executed upon success, after the data has been fetched.

Therefore, all subsequent code should be placed inside that function:

  $.getJSON("json/data.json", function(json) {
    const data = json;
    const record = data.filter(r => r.datasetID === datasetID);
    const vernacularName = record[0].vernacularName;
    $_SESSION["v"] = vernacularName;
    document.getElementById("demo").innerHTML = vernacularName;
  });

Additional note: Given that you seem to be utilizing ES6+, it is advisable to avoid using var unless necessary. Instead, opt for let. More information can be found here and in this post. However, in this scenario, since everything in your code remains constant, sticking to const is suitable.

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

Step-by-step guide to creating a transition effect when the input changes

I'm looking to add a unique effect to my dropdown menu My goal is to create an effect in which the placeholder moves up and the new value seamlessly takes its place, using JS, jQuery, CSS, and HTML. View before transition View after transition ...

Issue with box shadow appearing incorrectly as element content increases in size while the body has an image background

After applying a box shadow to the header div, I noticed that the box shadow doesn't display properly when the hidden elements within the header are revealed. <div id="header"> <div id="logo"> <a href="#"><img src="logo.png" ...

What is the quickest method to perform a comprehensive comparison of arrays and combine distinct objects?

I am currently working with NextJS and Zustand and I have a state in Zustand that consists of an array of objects: [{a:1, b:2}, {a:2, b:3}] Additionally, there is another incoming array of objects that contains some of the existing objects as well as new ...

Issue with Ag-Grid's getRowClass not locating the appropriate CSS styling

I am facing a simple challenge at the moment. My goal is to dynamically change the background color of my rows, with the intention of incorporating this feature when expanding or contracting groups. Currently, I am attempting to utilize gridOptions.getRow ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

decoding JSON information on the Android platform

I encountered a null pointer exception in the getView() method within the ContactinfoAdapter class. The problematic line is: busViewHolder.txt1.setText(c.getId()); Any suggestions on how to resolve this issue? I've included both the Contactinfo and ...

What is the best method for retrieving data from a website using Python and formatting it as either JSON or XML?

Looking for assistance with extracting specific information from various webpages? Provide a URL and extract details such as contact number, address, href links, names of individuals, and more. While it's possible to extract page source using known ta ...

Struggling to successfully pass an array as an API response from Express to the Front End. Looking for any recommendations or

As someone who is new to working with Express and APIs, I am currently attempting to send an array of JSON objects from the server to the client. To illustrate this process, here is a straightforward example: Server-side (Express, router file) router.get( ...

Show a table with rows that display an array from a JSON object using JavaScript

My current code includes JSON data that I need to display in table rows, but I'm struggling to understand how to do so effectively. The output I am currently seeing is all the rows from the array stacked in one row instead of five separate rows as in ...

Error in the execution of the if statement within $(window).width() when it is not supposed to be

Hello everyone, I'm facing an issue with the jQuery $(window).width when using if statements. It seems that my function is still running even when the window width is smaller than 991 pixels, although my if statement specifies that it should run only ...

Troubleshooting Problems with Ajax Servlets

When I perform a search, the results are returned and shortly after, the page redirects to a servlet displaying raw JSON data. It's a bit confusing for me. This JSP form submission: <form class="col-lg-12" action="./urllinks" method="GET" id="sea ...

The struggle of accessing child components using ViewChild in Angular

I am facing an issue with a dialog box that is supposed to display a child component separately. Below is the code for the child component: @Component({ selector: 'userEdit', templateUrl: './edituser.component.html', styleUrls: [ ...

The comparison between transmitting objects as JSON versus sending objects of a specified class

I have multiple web services running on Tomcat servers with Java backend. When one of the services queries for data from another service, it returns the result as a JSON string. I am currently using the JSON library provided by json.org to parse this infor ...

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

Persistent hover effect for collapsible accordion panels when closing them

My simple accordion features a functionality where a class of .open is added to the title + content group when you open a panel for styling purposes. Everything works smoothly, but I've noticed on my phone that after clicking to close a panel, the hov ...

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

Error occurred while looking for user by ID in the everyauth

I previously had a working example with express 2.*, but now I am transitioning to version 3.*. The issue arises during authentication with Facebook, causing some problems. Everything works fine until everyauth makes the GET request to Facebook and then re ...

Utilize module.exports to export objects containing callback functions

I am currently diving into the world of writing my own modules for nodejs. My goal is to create various objects that I can use throughout my application. Here is the result I am aiming for: //assuming we have a database: Person_table(ID int A_I, NAME var ...

An anomaly where a mysterious symbol appears in front of every dollar sign in an HTML document

I have a code written in AngularJS to display the amount in dollars. However, there is an unwanted " Â " character appearing before every " $ " character in the HTML. I am looking for a way to remove this character. Your help is greatly appreciated. Thank ...

Steps to configure Jackson to exclude a specific `get()` method from object serialization

In my class titled Project, I have the following code: @Transient public List<Release> getAllReleases() { List<Release> releases = new ArrayList<Release>(); ... return releases; } During serialization of a project object, th ...