JavaScript problem encountered when using the forEach() function on $el

I am encountering an issue where I am unable to access the element value inside the forEach() function

var filtered = rawData.map(function(x){
        return {
          state       : x.state,
          active      : x.active,
          deaths      : x.deaths,
          recovered   : x.recovered
        };
})

Trying to utilize the above in the following loop :

for(i=1; i<=filtered.length; i++){
        let tr = document.createElement("tr");
        tr.setAttribute("align","center");    
        document.querySelector('tbody').appendChild(tr);

        ndata = ['state', 'active', 'deaths', 'recovered']
        ndata.forEach((el, k) => {
          let td$k = document.createElement('td');
          td$k.innerText = filtered[i].$el;        // <-- ERROR //
          tr.appendChild(td$k);
        }); 

An error message is displayed by the browser : app.js:201 Uncaught TypeError: Cannot read property '$el' of undefined

Answer №1

It seems that the solution to calling the value dynamically worked for me, although I did have to make a small adjustment by starting the loop at i=0 instead of i=1 as mentioned previously.

ndata = ['state', 'active', 'deaths', 'recovered']
            ndata.forEach((el, k) => {
                let td$k = document.createElement('td');
                td$k.innerText = filtered[i][el];       
                tr.appendChild(td$k);
            });

Answer №2

To retrieve properties from an object, we have two options: the dot notation and the bracket notation. For example:

object.property
object['property']

In this case, el is not a property of the object filtered[i]. Rather, it is the key value represented as a string. Therefore, we must use the bracket notation like so:

td$k.innerText = filtered[i][el];

To learn more about this topic, refer to the documentation on Property Accessors.

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 DateTimePicker onChange event malfunctioning

Issue with JS datetimepicker onChange event not functioning. Attempts have been made using OnSelect, OnClose, OnChange, OnHide, OnChangeMonth to trigger the datetimepicker event, but none of them seem to be effective. <input type="text" class="form-co ...

The admin-ajax.php file in WordPress consistently fails to return any value other than

I developed a WordPress ajax plugin, but I am facing an issue where admin-ajax.php always returns 0 and the plugin doesn't work as expected. Here is the code I have implemented: add_action( 'wp_ajax_example_ajax_request', 'example_aja ...

Retrieving data from a database using twig

In my PHP code, I currently have the following: $vals['followers'][] = R::find('follow', 'following_id=?', array($_GET['id'])); This code returns all followers in the "follow" table with a following_id that matche ...

How to download an Excel file (xlsx) using AngularJS and WebApi

I am currently working on a project that requires me to download a report in xlsx format. Despite successfully generating the report file on the server and receiving it on the client side, I am facing an issue where the file is not opening and is resulting ...

Sending reference variable from Angular input type=file

I am currently learning Angular and I have implemented a feature where a list of PDF files is displayed using an array called pdfs. In my template, these PDF files are parsed into "card" elements for better visualization. The issue arises when I attempt ...

Creating a specialized feature for saving form data with React Admin

Within my react-admin application, I am faced with a scenario where I have a list of items accompanied by two separate buttons: "Create using email" and simply "Create". The "create" button utilizes the functionality provided by the data provider, which is ...

Sending a POST request results in both the execution of the THEN and CATCH

I am encountering a strange issue with my submit function, which is used to save an article. Despite receiving a success response code of 200 in the browser, both the 'then' success branch and the 'catch' error branch are triggered simu ...

Guide on incorporating the ":gt" filter from sizzle into vanilla javascript

I am currently working on adapting a jQuery plugin to be compatible with the AngularJS JQlite API, but I have encountered some challenges along the way. Here is an overview of the plugin: (function (e) { var $product = $('#product'), ...

What is the best way to show the interior color of a cube in three.js?

My plan is to create a room using THREE.js starting from a basic cube. Here's what I have written so far: function loadModelcube() { console.log("Function executed successfully"); cube.traverse( function( node ) { if( node.material ) { ...

SystemJS is loading classes that are extending others

In my Angular2 application, I have two classes where one extends the other. The first class is defined in the file course.ts (loaded as js) export class Course { id:string; } The second class is in schoolCourse.ts (also loaded as js) import {Cours ...

Accessing Route Parameters from Any Component

If my URL follows this structure: /blog/[post_id]/something What's the best practice for passing $post_id to any component within the tree? I'm familiar with retrieving route parameters using getInitialProps, but I struggle with passing values ...

I am experiencing an issue where Discord.js is unable to assign a role to a new member upon joining my server

I'm trying to set up my bot to automatically assign a specific role to new members when they join the server. However, I keep encountering a strange error that I can't seem to figure out. Here is the code snippet in question: const { GuildMember ...

Managing Input Type Dropdown Selections Using Jquery

I am currently in the process of developing a website. On this website, there is a form that includes 3 dropdown menus as shown below. I would like to implement a feature where selecting the number 5 from the Adults menu will automatically display 5 in the ...

Issue with Jquery .ajax function returning an object even after it has already moved on to the next line of code

I'm currently working with JQUERY and AJAX, and it seems like the function is somewhat functional but there's a glitch that occurs after the next line of code runs. This issue causes the script to add a null value when trying to insert the object ...

What is the best method to prevent next.js components from overlapping one another?

I recently created a website using next.js and noticed an issue in my index.js file. There is a div that houses the main components of the site: class Page extends Component { render() { return ( <div className={styles.container}> ...

div maintain aspect ratio while scaling

My current layout is structured like this: HTML <div id="container"> <div id="zoomBox"> <div class="box"></div> <div class="box"></div> <div class= ...

Tips for securing a navbar in material ui

https://i.stack.imgur.com/CYfmQ.png In my current React project, I am facing an issue with aligning components within the Material-UI AppBar Component. My aim is to achieve a seamless and perfectly straight alignment for three key elements: a logo image, ...

Codeigniter raises an error message stating, "No file selected for upload," in cases where data is transmitted via Ajax

Having trouble inserting form data using Ajax and Codeigniter - encountering a 'You did not select a file to upload' error specifically with file uploads. Need help passing input file data through jQuery ajax. Below is the jQuery code snippet: ...

Zingchart encounters issues when attempting to plot a CSV file containing over 10 columns

Situation: I want to create a Zingchart graph from a CSV file containing 37 columns. The header in the CSV file will be used as the legend for the graph. Issue: When I define less than 10 elements in the header (including the X-axis name), everything wo ...

What is the process of invoking a secondary "external" function with Nodejs, Expressjs, and bluebird?

Struggling with creating a nodejs application, a new area for me. I've managed to work with Promises and fetch data from a database. Take a look at the code below: myModel.js var express = require('express'); var app = express(); var Promi ...