What could be causing the issue of a Javascript array not filling inside a loop, even though it functions properly

I have a JSON dataset and I'm trying to extract the information of individuals who haven't paid their dues. Initially, when running the code with the if statement commented out, it works perfectly fine - giving the expected output in both the console and the HTML page where only a div with id=demo is present. However, upon uncommenting the if statement, while the console logs the correct results, the HTML page displays two (instead of three) lines with "undefined". This issue has left me puzzled as I've run out of ideas on what else needs to be modified.

var data;
data = [{
        "dues paid": "",
        "name": "john",
        "age": "18",
        "city": "Jamestown"
    },
    {
        "dues paid": "100",
        "name": "marvin",
        "age": "27",
        "city": "Dallas"
    },
       {
        "dues paid": "100",
        "name": "janice",
        "age": "22",
        "city": "Denver"
    }
 ]
let arr = [];
let checkbox = document.getElementById("check");

function setup() {
  let strLine = ""; 
  let checked = checkbox.checked;

  if(checked)
  for (var i = 0; i < data.length; i++) {
    if (data[i]['dues paid'] !== "" ){
      console.log(i,data[i]['name']);
      arr.push(data[i]['name'] );
      strLine = strLine + arr[i] + "\<br>";
    }
  }
  else
  for (var i = 0; i < data.length; i++) {
    //if (data[i]['dues paid'] !== "" ){
      console.log(i,data[i]['name']);
      arr.push(data[i]['name'] );
      strLine = strLine + arr[i] + "\<br>";
    //}
  }
  document.getElementById("demo").innerHTML = strLine;
}

document.getElementById("test").onclick=setup;
With if: <input type="checkbox" id="check"/><br/>
<button id="test">Test</button>
<p>Output below</p>
<div id="demo"></div>

Answer №1

When using the if statement, keep in mind that the indexes of arr may not align with the indexes of data. Once an element is filtered out, the alignment of indexes breaks. This means that arr[i] will not necessarily contain the name that was just pushed.

Instead of using arr[i], consider placing data[i]['name'] inside strLine.

var data;
data =[{
        "dues paid": "",
        "name": "john",
        "age": "18",
        "city": "Jamestown"
    },
    {
        "dues paid": "100",
        "name": "marvin",
        "age": "27",
        "city": "Dallas"
    },
       {
        "dues paid": "100",
        "name": "janice",
        "age": "22",
        "city": "Denver"
    }
 ]
let arr = [];

function setup() {
  let strLine = ""; 
  
  for (var i = 0; i < data.length; i++) {
    if (data[i]['dues paid'] !== "" ){
      console.log(i,data[i]['name']);
      arr.push(data[i]['name'] );
      strLine = strLine + data[i]['name'] + "<br>";
    }
  }
  document.getElementById("demo").innerHTML = strLine;
}

setup();
<div id="demo"></div>

Answer №2

If you want to filter through an array in JavaScript, you can utilize the Array.filter and Array.map methods. Check out more information on Array.filter and Array.map.

const outstandingUsers = data.filter((user) => user['dues paid'] !== '').map((user) => user.name); // Returns ["marvin", "janice"]

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

Dealing with nested JSON structures in reqwest: A comprehensive guide

My current project involves utilizing reqwest library to execute a GET request on . Sending a request to a single-level json endpoint like is straightforward use std::collections::HashMap; fn main() { let body = reqwest::blocking::get("https://h ...

Unable to impose a restriction on the number input field limit

My input field has a type of "number" with the min and max attributes applied to limit user input. However, I am facing an issue where users can still enter values beyond the set limit. How can I prevent users from entering values above the specified lim ...

Visualizing connections between elements using SVG from JSON data files

As a newcomer to D3, I am facing challenges in visualizing my json file. My task involves plotting the locations (sites) as circles with their radius determined by the "amount" value. The concept of working with nodes and links is causing me great confusio ...

Local directory system for organizing users' files and folders

My website is built using mean-stack technology. I utilize the File System to create folders and write files on servers. Here is an example of the backend code: router.post('/httpOnly/mkdir', function (req, res, next) { var fs = require(&apo ...

Exploring the power of regular expressions in Javascript when used between

Consider the scenario outlined in the text below I desire [this]. I also desire [this]. I do not desire \[this] I am interested in extracting the content enclosed within [], but not including \[]. How should I approach this? Currently, I have ...

After an error occurs, the Node.js Restify code will be executed

Within a Restify route, I have set up a router handler that calls a custom module for error checking. If the code encounters an error condition, it returns next(err) and displays the error message in the browser. However, the code does not stop executing a ...

locate an inner div element

Here are two div elements: <body> <div id="divParent"> <div id="divChild"></div> </div> </body> What is the best way to select the divChild element using JavaScript? ...

Angular HTML is throwing an error related to object arrays

Is there a way to display only specific fields of an array? <div class="form-check" *ngFor="let periodo of filterPeriodos()"> <div>{{periodo.periodos | json}}</div> <input class="form-check-input mr- ...

Using MongoMapper with Rails to efficiently render arrays in views

In my Rails application, I have a controller that retrieves data from MongoDB. The specific field I need is actually an array, and I want to display it in an erb view. Currently, my workaround involves setting the JavaScript variable directly in the view ...

Pass a Json object as a parameter to a Web Api controller in a .NET Core application

This code snippet utilizes Google API with Javascript var output = new Object(); output.PlaceID = place.place_id; output.Longitude = place.geometry.location.lng(); output.Latitude = place.geometry.location.lat(); $.ajax({ headers: { 'Acc ...

React State not refreshing

Currently tackling a challenging e-commerce project and facing an obstacle with the following component: import React, { useEffect, useState } from 'react'; const Cart = () => { let [carts, setCarts] = useState([]); let [price, se ...

Using Jquery Mobile to make an AJAX POST request with XML

Is it possible to use this code for XML parsing? I have successfully parsed using JSON, but there is no response from the web service. This is the status of the webservice: http/1.1 405 method not allowed 113ms $j.ajax({ type: "GET", async: false, ...

How to simulate loadStripe behavior with Cypress stub?

I am struggling to correctly stub out Stripe from my tests CartCheckoutButton.ts import React from 'react' import { loadStripe } from '@stripe/stripe-js' import useCart from '~/state/CartContext' import styles from '. ...

Tips for Customizing the Appearance of Material UI Select Popups

My React select component is functioning properly, but I am struggling to apply different background colors and fonts to the select options. https://i.stack.imgur.com/kAJDe.png Select Code <TextField fullWidth select size="small" nam ...

Is there a way to automatically zoom in when clicking on a marker and centering the map to that

I have integrated a map into my project where I am currently plotting random coordinates. These coordinates are stored in a data table and everything is functioning smoothly. However, I am facing an issue with implementing a zoom feature using the panTo m ...

When using a wildcard router in Node.js/Express.js, the static router may not be recognized

While using this specific route along with my other routes, I encounter an issue with serving static files: var public_dir = path.join(__dirname, 'public'); app.use('/public', express.static(public_dir)); However, when I add the follo ...

Invoking a class method in Javascriptcore on iOS

I'm currently trying to comprehend the inner workings of JavascriptCore. Initially, I attempted calling a single function. Now, my focus has shifted to invoking a function within a class. This is what my javascript code looks like: var sayHelloAlf ...

java.text.ParseException: Unable to parse date "Friday, September 12th, 2014 at 11:22:46 PM IST"

I am currently utilizing the Jackson mapper to directly map a JSON request to a Java object. For handling dates, I have implemented CustomDateSerializer for serialization and CustomDateDeserializer for deserialization in the getter and setter methods respe ...

What is preventing me from breaking out of the for loop when the condition is no longer true?

To terminate the cycle when the user inputs "0 00 00", use the following code snippet: main() { int i, o[128], m[256], s[256]; for(i = 0; o[i] != 0 && m[i] != 00 && s[i] != 00; i++) scanf("%d %d %d", &o[i], &m[i], & ...

Adjusting solely the depicted data sets in the Highcharts.js library

I have a spline chart with 10 different curves on it - When the page is first loaded, none of the charts are visible as I have set "visible" to false. Users will then click on the curve(s) they want to see. I am looking for a way to dynamically change the ...