When validating an array in JavaScript, it is important to note that not all elements may be displayed. Only the last variable of each element will

I am encountering an issue with validating an array of objects, specifically a table with rows where each row represents an object. The problem is that no error message appears if there is an error in the middle row of the table. However, if there's an error in the last row, it does show an error message. Can someone assist me in resolving this?

Initially, I attempted using a for loop:

for (i=0; i<schoolarray.length; i++) {
    if (schoolarray[i]['school name'] === "") {
       alert('School name is empty');
    } else if (schoolarray[i]['school name'] !== "") {
        alert('School name is not empty');
    }
    if (schoolarray[i]['school street'] === "") {
       alert('School street is empty');
    } else if (schoolarray[i]['school street'] !== "") {
        alert('School street is not empty');
    }
    if (schoolarray[i]['school add'] === "") {
       alert('School address is empty');
    } else if (schoolarray[i]['school add'] !== "") {
        alert('School address is not empty');
    }
}

The error messages are not displaying correctly as different iterations yield different element messages.

Subsequently, I tried a foreach loop below with a similar issue. Can anyone provide suggestions?

School Array: [ { school name: "First School", school street: "First Street", school add : "First Address" }, { school name: "Second School", school street: "Second Street", school add : "Second Address" }, { school name: "Third School", school street: "Third Street", school add : "Third Address" } ]

if (schoolarray.length > 0 ) {
    schoolarray.forEach(function(schoolObject, index) {
        console.log(schoolObject['school name']);
        Object.keys(schoolObject).forEach(function(prop) {    
            if(schoolObject['school name'] === "" ) {
                alert('Please enter the school name');
            } else if (schoolObject['school name'] !== "" ) {
                alert('Good');
            }   
        });
    });
}

Answer №1

Your initial `for loop` is incorrect because it includes multiple `if` and `elseif` statements unnecessarily. You only need to check if the property `school name` is empty or not.

In the `forEach` loop, you already have access to the school object, so there is no requirement for `Object.keys`.

const schoolarray = [{
    "school name": "first school",
    "school street": "first street",
    "school add": "first add"
  }, {
    // Empty
    "school name" : "",
    "school street" : "second street",
    "school add" : "second add"
  }, {
    "school name" : "third school",
    "school street" : "third street",
    "school add" : "third add"
  }];

if (schoolarray.length > 0 ) {
    schoolarray.forEach(function(schoolObject, index) {
        if(!schoolObject['school name']) {
            console.log('Please enter school name', schoolObject);
        } else {
            console.log('School name is not empty: ', schoolObject['school name']);    
        }
    });
}

Utilizing a `for loop`

const schoolarray = [{
    "school name": "first school",
    "school street": "first street",
    "school add": "first add"
  }, {
    "school name" : "",
    "school street" : "second street",
    "school add" : "second add"
  }, {
    "school name" : "third school",
    "school street" : "third street",
    "school add" : "third add"
  }];

for (i=0; i<schoolarray.length; i++) {
    if(!schoolarray[i]["school name"]) {
        console.log('Please enter school name', schoolarray[i]);
    } else {
        console.log('School name is not empty: ', schoolarray[i]["school name"]);  
    }
}

PS: It is advisable not to use `alert` as it can block the window repaint process.

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

Angular 4: Utilizing reactive forms for dynamic addition and removal of elements in a string array

I am looking for a way to modify a reactive form so that it can add and delete fields to a string array dynamically. Currently, I am using a FormArray but it adds the new items as objects rather than just simple strings in the array. Here is an example of ...

Fixing extended properties on an express request can be done by following these steps

I've been working on a JavaScript middleware where I can extract user information using the "req" object in the route handler. When I log currentUser, I get the expected value, but I'm encountering a TypeScript error warning: Property 'curre ...

Retrieve the visitor's IP address following the submission of an AJAX form

Currently, I am facing an issue with my HTML form and JavaScript method integration. Whenever a visitor submits the form, a JavaScript method is triggered which sends an AJAX request to a PHP file on my server. The problem arises when trying to retrieve ...

Nuxt.js has exceeded the maximum call stack size

Recently, I started working on a nuxt.js/vue project using a pre-built starter template. However, I have been encountering numerous error messages such as "Maximum call stack size exceeded." It's quite challenging to pinpoint the exact source of these ...

Tips for producing/reserving cropped images from a photo? (includes converting images to base64 format)

Imagine having two square datasets taggedImages: { 0: {id:0, left:100, top:100, thumbSize:100, type: 'A', seasons: ['All', 'All']}, 1: {id:1, left:200, top:200, thumbSize:100, type: 'B', seasons: ['All&apo ...

Include the <script> tag in the HTML code for an iframe without running it

Currently, I am working on an HTML code that involves memory for an Iframe. Interestingly, whenever I use the append function, it not only executes the code but also carries out its intended task. html = $(parser.parseFromString($("#EHtml").val(), "text/h ...

The display:flex property with justify-content:space-around is malfunctioning in React and causing issues

I've been trying to troubleshoot the issue with my header, but so far I haven't found a solution. Could you please take a look at my code first? // Code simplified for clarity, no need to worry about variables const Header = () => { return ...

This React.Js application hosted on Heroku is optimized for use on Chrome Desktop browsers

Just finished completing a React project that retrieves News Articles and presents them. Recently launched it on Heroku, but I'm encountering an issue where only Chrome on Desktop seems to be able to run it. Both Safari and Firefox are showing the sa ...

Show the image on top of the div block as the AJAX content loads

Implementing this task may seem easy and common, but I am struggling to figure it out! What should take five minutes has turned into an hour of frustration. Please lend me your expertise in getting this done. I have a div container block: <div cla ...

When attempting to remove an object from an array in Vue.js, an error may occur stating that the property of the

In my project, I am working with 3 files: App, BlogList, BlogItem. The goal is to enable users to delete a post if they choose to. However, when using splice method, I encountered the following error: The property or method "removePost" is not defined o ...

Exploring the React component life cycle: Understanding the distinction between render and return, and what happens post-return

This question pertains to the concepts surrounding react component life cycles. Below is an example code snippet provided as a general reference. const Modal = ({ className, variant, width, withCloseIcon, isOpen: propsIsOpen, onClose: tellParen ...

Flattening an array of Map in Typescript involves combining all the

I am working with an array containing entries of type Map<string, number> Is there a way to flatten this array into a single map? Map<string, number>[] converted to Map<string, number> Appreciate any help on this matter. ...

Rearrange Material UI styles in a separate file within a React project

Currently, I am developing an application utilizing material-ui, React, and Typescript. The conventional code for <Grid> looks like this: <Grid container direction="row" justifyContent="center" alignItems="center&q ...

What is the reason for the absence of the $.ajax function in the jQuery package designed for node.js?

Here is my code sample, which I would like to use for practicing with jQuery's ajax function. Note that I have already installed the jQuery package using npm install jquery: var $ = require('jquery'); var remoteValue = false; var doSometh ...

Trouble arises when attempting to use JavaScript, JSP, and JSON in conjunction with

I am in the process of creating a client-server application where I send a request from the client to the server using a JSON object for registration. However, despite receiving a JSON response with an "OK" field as expected, the client keeps triggering th ...

What is the process to activate a resize event with nvd3?

I am trying to figure out how to make the resize event trigger on nvd3 for AngularJS. The issue I am facing is that when I add line breaks in the labels of the pie chart and then resize the window, the labels revert back to a single line. What I want is ...

Ways to navigate private property using the App Component in Angular 4

I have successfully implemented code in my app component to retrieve the current URL and display it in app.component.html. app.component.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Compone ...

Node js - Looping Through Loading

I am facing an issue with my Node.js application. It runs perfectly fine on my local environment, but when I try to run it on my server using forever, the page just keeps loading without displaying anything. There seems to be no response and it gets stuc ...

The useSelector value remains undefined within the handleSubmit button in a React component

Once a user fills out and submits the form, the action is triggered to call the API. Upon returning the postId, it is stored in the reducer. The main React component then utilizes useSelector to retrieve the latest state for the postId. However, when attem ...

Set the minimum height of a section in jQuery to be equal to the height of

My goal is to dynamically set the minimum height of each section to match the height of the window. Here is my current implementation... HTML <section id="hero"> </section> <section id="services"> </section> <section id="wo ...