Looping through nested variables in a JSON file

In the midst of developing a discord bot that stores economic data for its users. The script below is designed to iterate through each file saved in a directory (JSONs named after the user's ID), containing an array of "buildings" or items they possess.

Here's a condensed JSON snippet of the table I'm utilizing to retrieve information on the buildings owned by the user (note: there are multiple categories and various buildings within each category):

{ 
    "small_buildings" : [ 
      {
        "description" : "basic description",
        "name" : "basic item",
        "income" : 500,
        "startprice" : 30000,
        "id" : 1
      }
    ]
  }

The code provided iterates through each file, followed by each category. However, the third loop attempting to cycle through each building (specifically at "for (var e in econvar.category){") runs from 0-15 without finding a suitable id match.

"econvar" denotes the file path of the json table.

files.forEach(function (file) {
      let jsonArr = require("C:/discordbot/econdata/" + (file)) // fetch the initial file
      jsonArr.forEach(function(i){    
          console.log("reached step 2 " + i)
          for(var category in econvar) { 
              console.log("reached step 3 " + category)
              for (var e in econvar.category){ 
                  console.log("reached step 4 " + e)
                  if (e.id == i) {
                      console.log("reached step 5 " + e.income)
                      total += e.income;
                      channel.send("totalcount: " + total)
                  }
              }
          }
      })
  });
  

I've experimented with altering the variables e and econvar.category along with employing different looping methods, yet I still encounter issues like "reached step 4 undefined," "reached step 4 (followed by numbers 0-15)," or encountering errors.

Your assistance in resolving this matter would be greatly appreciated. Thank you for your patience in understanding the intricacies involved.

Answer №1

Ensure your final for loop is written like this:

 for (var element in category){ // iterating through each element in the category 
    ...
 }

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

JavaScript constructor functions may trigger ReSharper warnings for naming convention

When it comes to JavaScript coding, I personally prefer using PascalCase for constructor functions and camelCase for other functions. It seems like my ReSharper settings are aligned with this convention. However, when I write code like the following: func ...

Removing attribute text from the output in Azure SQL: A step-by-step guide

Is there a way to remove the "attribute" from Azure SQL output for json path? Let's consider the following test data: create table test (country varchar(50), city varchar(50)); insert into test values ('US', 'New York'); insert ...

What are the steps to modify the authorization header of an HTTP GET request sent from a hyperlink <a href> element?

I have a unique Angular application that securely saves JWT tokens in localstorage for authentication purposes. Now, I am eager to explore how to extract this JWT token and embed it into an HTTP GET request that opens up as a fresh web page instead of disp ...

The Bootstrap DateTime Picker is not displaying correctly; it appears to be hidden behind the screen

Need assistance with displaying the full datetime picker on the screen. I attempted using position:relative but it's not working as expected. Can someone please help me with this issue? HTML code : <div style="position:relative"> <div class ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

Extract Individual Textures from a Single Texture File

Currently, I am working on developing a 2D tile-based computer game using JavaScript and jQuery. The game utilizes the Canvas element for rendering. One challenge I am facing is how to handle an image file containing multiple textures within a single file. ...

Passing events from one controller to another in AngularJS using methods such as $broadcast and $window.localStorage

Looking to dispatch an event to another controller, I am familiar with techniques involving $rootScope.$broadcast, $scope.$emit, and then listening for the event using $scope.$on. This is a common approach, but in my project, controllers are initialized i ...

Converting an Image to Memory Stream in JavaScript

Incorporating the jquery.qrcode library, I am able to create a QR code image that is output in the following format. <img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAA ...

Serve vast in-memory array using ESPAsyncWebServer

I am attempting to serve a sizable float array with 8192 values from the ESP32 Heap using the ESPAsyncWebServer library for ArduinoIDE. The microcontroller I'm using is an ESP32 devkit c, and my goal is to access the array through a web browser. Here ...

Python: Exploring Multi-Index Looping

Creating a loop in Java or C is very straightforward and simple. for (int i = 0; i <arr.length()-1; i++) { for (int j = i+1; j <arr.length(); j++) { //process } } However, I am having trouble replicating this in Python. For instance: for ...

Why is my conversion method inconsistent in producing accurate binary values from decimals when iterating through a sequence of integers in a character array using Java?

As a Java beginner, I'm currently tackling a problem related to counting consecutive integers in binary representations of numbers. The input numbers are converted to binary using a method called conversion. This binary form is then stored in a chara ...

Ways to refresh MySQL data in an AJAX container as outcomes are being fetched?

Can anyone help me understand how to refresh a <div> using AJAX to display records fetched from a MySQL database? The challenge is to show each result in the <div> for 30 seconds before reloading to display the next result. Below is the struct ...

NodeJS application does not acknowledge the term "Require"

I have completed the steps outlined on http://expressjs.com/en/starter/installing.html to set up my express NodeJS application. Following the installation, we navigated to the "myapp" directory and installed the "aws-iot-device-sdk" from https://github.com ...

IE8 and IE9 encountering "Access is denied" error due to XML causing XDomainRequest (CORS) issue

Sorry if this seems repetitive, but I am unable to find a definitive answer to similar questions. Whenever I attempt to make a CORS request for XML, I consistently encounter an "Access is denied" JavaScript error in IE8. The code I am using is based on t ...

Will the package versions listed in package-lock.json change if I update the node version and run npm install?

Imagine this scenario: I run `npm install`, then switch the node version, and run `npm install` again. Will the installed packages in `package-lock.json` and `node_modules` change? (This is considering that the packages were not updated on the npm regist ...

Error encountered while generating Next.js static website in production

I am encountering errors when I try to export my project using npm run build. Oddly, everything works fine when I test with npm run dev. My code utilizes both getStaticProps and getStaticPath to fetch data from an API route. When I run npm run build I rec ...

What are the steps to resolve the issue of encountering the error message "Unrecognized custom element: <bot-ui>"?

I'm having some trouble setting up a chatbot screen with the "botui" and "vue-cli". Whenever I try to display the screen, I encounter an "Unknown custom element: " error. Below is the code snippet that I am using. Can you please help me figure out ...

Customize JSON format with Ninja Framework

Is there a way to customize the JSON format when returning JSON in a NINJA FRAMEWORK controller? return Results.json().render(MyPOJO); Definition of MyPOJO class @Entity public class MyPOJO { private String Name; private Strin ...

Sort all the iterable nested recursively

Can someone help me with recursively sorting all nested iterables within an iterable? For example: d = { 'e': [{'y': 'y'}, {'x': [{'2': 2, '1': 1}]}], 'x': ['c', &apo ...

Is it possible for me to determine the quantity of lines present in the text without any

I have a user-input field where individuals can enter information. The input can range from no information at all to as little as a single word or unlimited characters. However, my focus is on handling cases where the text exceeds three lines. To address ...