JavaScript - Retrieving nested elements within a JSON structure

Currently, I am dealing with a set of 4 JSON objects that contain nested data within them. These objects are all stored in an array named classes. Below is an example showcasing the format of one of these class objects:

let class_A = {
    professor: "Joey Smith",
    numberStudents: 25,
    courseCode: "COMS 2360",
    seating: {
        "FirstRow": {
            0: {
                firstName: "Sarah",
                collegeMajor: "English",
            },
            1: {
                firstName: "Bob",
                collegeMajor: "Computer Engineering",
            },
            2: { 
                firstName: "Dylan",
                collegeMajor: "Mathematics",
            }
        },
        "SecondRow": {
            3: {
                firstName: "Molly",
                collegeMajor: "Music"
            }
        }
    }
};

I'm currently facing difficulties in accessing the final fields within each class object (firstName and collegeMajor). I am only able to reach the indexes under each row number.

let classes = [class_A, class_B, class_C, class_D];
let classesAvailable = document.getElementById('classes');
let selectedClass = classes[classesAvailable.value];

for(rowNum in selectedClass.seating){
    for(index in selectedClass.seating[rowNum]){
        console.log(index);
        //console.log(selectedClass.seating[rowNum[index]].firstName);
                
    }
}

In this example, when I use console.log(index), the output is as follows:

0

1

2

3

However, I am unable to display the first name and college major of each student in every row. Even though I attempted to apply a similar approach by using console.log(selectedClass.seating[rowNum[index]].firstName), it resulted in the following error:

Cannot read properties of undefined (reading 'firstName')

If anyone has insight into what could be causing issues with my process, your input would be greatly appreciated.

Answer â„–1

output(classroom.seats[rowNumber][index])

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

Error message: The property '__isVuelidateAsyncVm' cannot be read because it is undefined

I'm encountering an issue with the code I have in this codesandbox link. The code features a form with validation and a disabled "Calculate" button that should only become enabled when all fields are valid. However, I'm receiving the error messag ...

Could somebody explain in simple terms how to correctly set up offline Google oauth2 with node.js?

When using a web browser, I follow these steps: let { code } = await this.auth2.grantOfflineAccess(); I then store the retrieved code in my database. Next, on the server side with node.js, I do the following: const { tokens } = await oauth2Client ...

Analyzing elements within an array to eliminate duplicates (PHP and MySQL)

I have a task involving PHP/MySQL that I am currently working on. At the company where I work (not in programming), we are gathering fax numbers and other data from customers to use in case of operational issues. The array structure is as follows: A ...

Caution: Function declared within the loop contains risky references to variable(s) no-loop-func in a forEach loop

Within my React project, there exists a straightforward .js file containing the code snippet below: let oldInfo function getChanges() { const newInfo = {}; let keys = ["name", "age", "sex"]; oldInfo = "one&q ...

Combining arrays with identical values into a new array?

I have a large array with multiple similar values, but I want to group all arrays with the same value into another array. Here's an example of the array: array(4) { [0]=> array(8) { ["symbol"]=> string(3) "aaaa" ["name"]=> ...

What can I do to ensure that the language-picker button retains the chosen value even after being clicked and the page is refreshed?

Just diving into JQuery. I've got this jquery code for a language-picker on a multi-language website. The issue is that after the page reloads in the selected language, the language picker defaults back to the original language displayed in the div t ...

Transmit JSON information to a Node.js server

Struggling with sending json data to my node server. I attempted the following: var req = { method: 'POST', url: 'http://33.33.33.15/user/signin', headers : { 'Content-Type' : 'application/ ...

SQL AJAX-driven cascading dropdown menu

I have a database consisting of 5 tables, each representing a subcategory of the previous one: countries states cities ZIPcode streets Currently, I have 3 dropdowns that are interdependent. For example, selecting countries: USA will show only the states ...

I am utilizing the useEffect hook along with Axios to fetch data from the backend. My goal is to retrieve two arrays of objects in order to render them on the

I am attempting to retrieve 2 arrays of objects from my MySQL database using Axios, but the console.log output '3' is showing an empty array. I'm not sure what's causing this issue. export default function Editar() { let {clienteId} = ...

Revamping a pie chart by incorporating a fresh dataset containing additional data points

I recently started learning D3 and have been exploring various pie chart tutorials. Specifically, I've been following the tutorials by Mike Bostock. http://bl.ocks.org/mbostock/1346410 However, I'm struggling with updating a donut chart from on ...

Adding multiple elements at specific indexes in Matlab

I have a question regarding inserting values into a large array A at specific positions using indexing. The values and positions to be inserted are stored in another array called B. Is there a way to achieve this assignment without having to use a traditio ...

Echo command fails to work with location.href

I am facing a small issue with my PHP echo. I have a JavaScript link function that is not working because the HTML code shows this type of link onclick="location.href="http://www.link.com/";". It's clear that this syntax won't work. However, if w ...

React Header Component Experiencing Initial Scroll Jitters

Issue with Header Component in React Next.js Application Encountering a peculiar problem with the header component on my React-based next.js web application. When the page first loads and I begin scrolling, there is a noticeable jittery behavior before th ...

Determine whether there are a majority of items that match in a list of n items. This algorithm has a time complexity of O(n log(n))

What is an efficient way to determine if any element in a list of n items appears more than n/2 times with a time complexity of O(nlogn)? The catch is that you can only compare if elements are equal, nothing else. I am struggling to improve upon the O(n^ ...

Executing Javascript in Python Environment

I'm currently working on developing an HTML document parser using Python. Since I have a strong understanding of jQuery, I am interested in leveraging its traversal capabilities to parse these HTML files and then send the gathered data back to my Pyth ...

Creating a dropdown menu in React

Imagine having an options array like the one below: options = [ { name: 'My profile' }, { name: 'Sign out' } ] public selectOptions(showOptions: boolean) { this.setState({ showOptions: !showOptions }) return options.map((opt ...

Troubleshooting a 400 error with Express and React: A step-by-step guide

When I check the browser console, I see this error message: `xhr.js:251 POST http://localhost:325/budget 400 (Bad Request) BudgetNew.js:30 catch AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: ...

Generating a 3D face using three coordinates in Three.js

Currently, I have implemented code that allows me to load, render, and display a STL object using Vue.js and Three.js. My goal now is to replace the currently selected plane with a new face. I've managed to extract the 3 vertices of the clicked-on fac ...

Tips for utilizing Selenium to acquire links from a webpage

Is it possible to retrieve the link location of a web element in Selenium? While we can easily obtain the text from a web element and use getAttribute("href") method to get the location of a hyperlink, my need is to extract all the links present. For insta ...

Custom option price calculation is not being displayed on the catalog product view page in Magneto 2

Just recently started working on Magento 2 and I need to activate the following functionality: I successfully implemented this functionality in version 1.9, but I'm unsure how to do it in Magento 2. If you have any ideas or suggestions to help me so ...