Adding items from the JSON data to a nested array at index i

In my project, I am working with two files: index.js and list.json.

My goal is to extract an element from list.json and insert it into a nested array following the structure [hour][visits per hour].

The hour refers to the index of the hour; for example, hour 12 corresponds to index 12. However, I keep encountering undefined errors in the console. Below, I will include a snippet to illustrate this issue.

Here is a sample from the json file, consisting of a total of 28 lines:

[
  { "time":"01:34:19", "visits": 37 },
  { "time":"02:03:21", "visits": 42 },
  { "time":"02:22:35", "visits": 51 },
  { "time":"02:43:54", "visits": 31 },
  { "time":"03:31:43", "visits": 24 },
  { "time":"03:38:01", "visits": 27 },
  { "time":"05:29:57", "visits": 36 },
  { "time":"05:54:08", "visits": 47 },
  { "time":"06:11:17", "visits": 49 },
  { "time":"07:22:03", "visits": 51 },
  { "time":"07:27:09", "visits": 55 },
]

Below is the JavaScript code attempt:

let json = require('./list.json');

let visitsPerHr = [];
visitsPerHr.length = 24;

//To prevent type error in the second loop
for (let x = 0; x < 24; x++) {
    visitsPerHr[x] = x;
}

let hour = -1;
let visitCount = -1;

for(let i = 0; i < json.length; i++){

    //Extracting and parsing hour
    hour = json[i].time[0] + json[i].time[1];
    hour = parseInt(hour, 10);

    //Extracting and parsing visits
    visitCount = json[i].visits;
    visitCount = parseInt(visitCount, 10);

    //Adding visitCount to the relevant hour index 
    visitsPerHr[hour].push = visitCount;

}

I need assistance with correctly assigning visitCount to the corresponding hour index. As I iterate through each index (from hours 1 to 23), I should be able to retrieve all the visits for that particular hour.

An ideal outcome for hour 7 would look like this: [7][27,29,22]

However, the current result displays as follows:

2
undefined
2
undefined
2
undefined
2
undefined
5
undefined
6
undefined
6
undefined
6
undefined
6
undefined
7
undefined
7
undefined
7
undefined
7
undefined
7
undefined
8
undefined
9
undefined
10

This pattern continues until reaching hour 23.

Answer №1

let jsonData = require('./data.json');
let hourlyVisits = {0:0,1:0,2:0,3:0,4:0 ... 23:0};
for (let item of jsonData) {
    hourlyVisits[(new Date(item.timestamp)).getHours()] += item.numVisits;
}

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

Storing information in local storage as JSON using AngularJS

I am working on a form with the following fields: <form ng-submit="addState()"> <input ng-model="text1" type="text"> <input ng-model="text2" type="text"> <input ng-model="text3" type="text"> ...

Fixing a JavaScript conflict between the parent theme and the child theme in WordPress

Recently, I created a customized child theme based on the Divi Theme, tailor-made for integration with Buddypress. Everything was going smoothly until I encountered a conflict involving the commenting buttons due to a script. In my theme, there is a JavaS ...

JavaScript - The onkeypress event continuously adds text to the end

In my Angular application, I have implemented an input field with the onkeypress event handler to automatically remove any commas entered by the user: <input name="option" ng-model="main.optionToAdd" onkeypress="this.value = this.value.replace(/,/g ...

jQuery scrollTop animates to the start of the webpage

Upon loading the page, the div appears at the top of the screen but then jumps to its correct position once scrolling begins. To view the website, click on this link: calretirement.com/classes-test.php CSS: .register{position:fixed !important; bottom:1 ...

Increasing numerical values within an array using JavaScript

My goal is to enhance the functionality of this visualization by being able to increase or decrease the nodes in the hidden layers. I have attempted to achieve this by adding the following code: I am facing difficulties in adjusting the number of hidden l ...

Retrieve the value from a variable located outside an API function call

As I work on developing a chat application project that includes abusive text detection, I have encountered an issue with accessing data from the Perspective API. While I am able to set attributes within the API function, I face challenges accessing them o ...

I am sometimes experiencing issues with activating ajax code using Bootstrap 3 modal

I'm stumped trying to find a solution for this issue. Currently, I am utilizing the bootstrap modal to retrieve ajax content from a specified URL. To prevent content overlap, I am using $.removeData() when reloading the content. The problem arises w ...

How to create a model for an array object in Flutter

I am attempting to create a model array for my design table that resembles this structure. However, I am unsure of how to proceed with it. https://i.sstatic.net/KhZt2.jpg While referencing this link for my JSON array below, I encountered an error stating ...

What could be causing the sluggish performance of my JavaScript code?

Could someone offer insight into why my JavaScript code is performing slowly? Are there any optimizations I can implement to improve its speed? Thank you! $(document).ready(function() { /* Trigger animation when window is scrolled */ $(window).scroll( ...

Ways to separate a string based on changing values in Javascript

Given this unmodifiable string: "AAACCDEEB" I am looking to split it into an array whenever the value changes. In this scenario, I would end up with 5 arrays like so: [['A','A','A'], ['C','C'], [ ...

Vue.js - Capturing a scroll event within a vuetify v-dialog component

Currently, I am working on a JavaScript project that involves implementing a 'scroll-to-top' button within a Vuetify v-dialog component. The button should only appear after the user has scrolled down by 20px along the y-axis. Within the v-dialog, ...

Is it feasible to assess JavaScript expressions during compilation using Webpack?

I'm currently in the process of setting up webpack for a new project. This project is quite extensive and available in multiple languages. I am aiming to have each entry point in my project be represented by separate files in each language. The catch ...

Express Server React 403 Forbidden Error

Issue: When attempting to make a post request using the AXIOS library in React, I am receiving a 403 (Forbidden) error for http://localhost:5004/api/auth/login. Despite having installed cors on Express, the console continues to display the 403 error. My c ...

Using React and Material-UI to dynamically populate a table with data retrieved from

Material ui table utilizes data in a specific format. rows: [ createData(1, "dashboard", "details"), createData(2, "product", "product details"), ].sort((a, b) => (a.id < b.id ? -1 : 1)) When the API responds with data stored in st ...

Tips on how to modify JSON data retrieved from a MySQL database by utilizing Laravel or simply native PHP?

Recently, I made changes to my database table structure, switching the type of a column to longtext to accommodate JSON data. Now, I am facing an issue where I need to update a specific part of the JSON data after retrieving it using Laravel/PHP. I attemp ...

AngularStrap's bs-modal is failing to display content

I have a question, here is a Plunker with the code: http://plnkr.co/edit/SNFy2XcOBefUavG1QCqD?p=preview <button class="btn btn-default" data-template="customer.tpl.html" bs-modal="modal">New Customer </button> < ...

Having Trouble Fetching Library of Congress Linked Data with Node.js

Visit the Library of Congress techcenter page at to explore examples of accessing linked data. For instance: curl -L -H 'Accept: application/json' http://id.loc.gov/vocabulary/preservationEvents/creation Executing the above example will gener ...

Modify the state's value by updating it when your information is stored in an array

I am currently working with contact numbers stored in an array and utilizing native-base for data viewing. this.state = { leadProfile: { contactNumber: [ { "lead_contact_number": "0912 312 412312", "lead_contact_nu ...

Updating a query parameter with jQuery

Looking for a way to modify the value of a query parameter in a URL using jQuery. There are two example URLs: www.domain.com/?id=10&name=xxx and www.domain.com/?name=xxx&id=10 I want to update the id parameter to something like www.domain.com/ ...

Experiencing difficulties connecting with aspx while using Ext JS 4.2

Currently, I am facing an issue with making a call to an ASPX URL as the return keeps coming back as a failure. I have successfully used this URL in previous programming projects, but this is my first time utilizing it with Ext JS. Despite researching dif ...