Getting data from JSON to fill an array: A step-by-step guide

I am currently facing an issue where I am trying to incorporate data from a JSON file into my array, but for some reason, the information is returning as 'undefined' because nothing is being created in my array. Below are the contents of the JSON file:

   "histogram": [ 
      {  
         "type": "Comedy",
         "count": 4
      },
      {  
         "type": "Action",
         "count": 5
      },
      {  
         "type": "Romance",
         "count": 6
      },
      {  
         "type": "Drama",
         "count": 1
      },
      {  
         "type": "SciFi",
         "count": 4
      }
   ]
}

The current code that I have been utilizing involves using the push() function to add information, however, it doesn't seem to be functioning correctly at the moment. Here is the snippet of the code in question:

let movies;
function preload() {
movies = loadJSON('movies.json');
}

count = [];

var c0 = movies.histogram[0].count;
count.push(c0);

I would greatly appreciate any assistance or guidance with this matter. Thank you!

Answer №1

To ensure that the variable movies is filled with data, you must first invoke the function preload:

count = [];
preload();

It is important to note that the function loadJSON likely operates asynchronously. Therefore, you should adjust your code as follows:

async function preload() {
  let data = await loadJSON("films.json");
  movies = data;
}

count = [];
(async () => {
  preload();
  var c0 = movies.histogram[0].count;
  count.push(c0);
})();

The use of an async IIFE simplifies the process of executing asynchronous functions correctly.

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

Is there a way to connect and interact with a different ng-controller's ng-model within a separate ng-controller?

Is it possible to access the ng-model from another ng-controller and if so, how can it be done? In this scenario, I am using two controllers. The first controller has a model called mddl1, while the second controller does not have any other model. However, ...

Updating the JSON data with a new row

I am trying to dynamically add a new row to my JSON data when the user clicks on a link. Despite not receiving any errors, I am unable to see the updated JSON in my alert message. $(document).ready( function(){ people = { "COLUMNS":["NAME","AGE"], ...

Is there a specific side effect that warrants creating a new Subscription?

Recently, I had a discussion on Stack Overflow regarding RxJS and the best approach for handling subscriptions in a reactive application. The debate was whether it's better to create a subscription for each specific side effect or minimize subscriptio ...

Data binding in Vue does not function properly within functional components

Clicking the button will cause the number n to increase, but the UI will display it as constant 1. <script> let n = 1 function add() { console.log(n) return ++n } export default { functional: true, render(h, ctx) { return (<div> ...

Utilizing NSURLConnection's Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [self.responseData setLength:0];(URL10) self.jsonData = [[NSMutableData alloc]init];(URL20) self.genderData = [[NSMutableData alloc]init];(URL30) } ...

Installing npm modules can be a time-consuming task when running docker-compose

I have been working on a project using Next.js and a PostgreSQL database in a Docker container. The setup of my project involves Docker Compose. However, I've noticed that when I run docker-compose up, the npm install command takes an incredibly long ...

Error message "TypeError: onClick is not a function" occurs when attempting to use a prop in a functional component

I am encountering issues while trying to utilize the onclick function as props. It shows an error message 'TypeError: onClick is not a function' when I click. What should I do? 7 | <Card 8 | onClick={() => onClick(dish ...

The final condition of the ternary operator fails to render if the specified condition is satisfied

Having trouble identifying the issue with this ternary statement. The last element (blurredscreen) is not appearing when authStatus !== "authenticated". return ( <> <div key={"key-" + id}> {isO ...

Retrieve only the items from a JavaScript array where the index is below a specified value

My goal is to filter out all the items from the initialItems list that have an index lower than the current item. For example, if the current item is CM, I want to display QS, IT, and AB in a draggable dropdown menu. However, I'm unsure of how to prop ...

Dynamically extracting elements from a JSON dataset

I have an initial JSON template that is uploaded to a web platform by the administrator: { "age": 0, "name": "string", "interest": "string", "address": "string", "personalId": 0 } Users can then create their own JSON schemas based on ...

Error message: "jQuery is not defined and occurs exclusively in Chrome."

I've been using the following code to asynchronously load my JavaScript in the head section: <script type='text/javascript'> // Add a script element as a child of the body function downloadJSAtOnload() { var element4= document.creat ...

Saving, displaying, and removing a JSON document

As someone new to the world of JavaScript, I am encountering an issue with JavaScript and AJAX. I am aiming to create a function that allows me to add new elements with unique indexes. After saving this information to a JSON file, I want to display it on a ...

Is there a way to link my mapDispatchToProps with an onClick property in React?

I'm currently facing some challenges while trying to integrate redux into a basic react project I'm working on. It's actually a react 360 webvr project but I've noticed similarities with react native that make me believe it should work. ...

Loop through different JSON objects with unique values using ng-repeat

I am facing an issue with a JSON file that contains three different objects for each area, and I need some help. Here is an example: { "gebieden":"Antwerpen", "onderwerpen":"Gemiddeld netto inkomen per belastingsplichtige", "data_2005":"15084, ...

What is the best way to add Vue dependency using CDN?

For my project which is built using Kendo, Vue, .Net, Angular and jQuery, I need to incorporate https://www.npmjs.com/package/vue2-daterange-picker. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...

Guide to retrieving and showing specific items from a DropDownList in a Text box using JavaScript, HTML, and AngularJS

Can someone explain how to extract and select items from a DropDownList and display them in a Textbox using JavaScript/HTML/AngularJS? Here are more details: I have a dropdown list with many items. When I click on an item from the list, it should be dis ...

Removing a specific object from an array in Node.js

Here is the structure of my database.json file: { "opened_tickets": [ { "userid": "4", "ticketid": "customer_info", "opened_timestamp": "1662543404514" }, ...

Instruct npm to remove dependencies that are no longer necessary

After adding a few libraries to my package.json file, I realized that they are no longer needed. Is there a command line parameter for npm install that can be used to remove unnecessary packages from node_modules directory that are not in package.json anym ...

The functionality of Jquery-chosen appears to be malfunctioning when applied to a select element

I am encountering an unusual issue with Jquery-Chosen. There is a multi-select box within a pop-up where the options are populated using an ajax call. Strangely, Jquery-Chosen does not seem to work on it. However, if I use a static multi-select box in the ...

Step-by-step guide on printing barcode labels from a browser in ReactJS with the Wincode C342C printer

Has anyone here successfully printed from the client side using JavaScript/ReactJS to a Wincode c342c printer? I've installed the qz.io library to allow my JavaScript code to access the client's printer. I've managed to print a PDF as base6 ...