Iterate through a collection of JSON objects using JavaScript

Hello, I'm a beginner in Javascript and I am currently attempting to iterate over an array of JSON objects. However, I am facing issues with the code below that was designed to loop through a static array of JSON constants.

function saveAccount() {
    const userName = document.getElementById('user_name');
    const userPassword = document.getElementById('user_password');
    const formErrorMessage = document.getElementById('fillFormError');
    
    if(userName.value == '' || userPassword.value == '') {
        formErrorMessage.textContent = 'Please fill out all form fields!';
        formErrorMessage.style.color = 'red';
        event.preventDefault();
    } else {
        localStorage.setItem('userName', userName.value);
        const allUsers =  '[{"username":"test3","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="60140513145320080f140d01090c4e030f0d">[email protected]</a>","password":"123"},{"username":"test2","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4b0a1b7b0f684acabb0a9a5ada8eaa7aba9">[email protected]</a>","password":"123123"},{"username":"test1","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3d7c6d0d792e3cbccd7cec2cacf8dc0ccce">[email protected]</a>","password":"456456456"}]';//JSON.parse(localStorage.getItem('users'));
        for(var i = 0; i < allUsers.length; i++) {
            var user = allUsers[i];
            console.log(user.username);
            
            if(user.username == userName) {
                console.log('USERNAME FOUND!!!!!');
            }
        }
    }
}

The goal is to determine whether a username exists within the user array. console.log(user.username); -> returns undefined and the .parse method also triggers an error.

Answer №1

allUser is currently a string type, making it impossible to iterate over. Give this a try:

const allUsers =  [{"username":"test3","email":"<a href="/cdn-cgi/l/email-prote...plain about the issue.</a>","password":"456456456"}]

Answer №2

//Utilize JSON.parse to convert allUsers into an iterable format:

   var convertedAllUsers = JSON.parse(allUsers);
   for(var j = 0; j < convertedAllUsers.length; j++){
        if(convertedAllUsers[j].username == userName){
            console.log('USERNAME HAS BEEN LOCATED!');
        }
    }

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

Ways to access nested keys in a TypeScript object as well as an array containing objects

As I develop a form generator, my goal is to achieve type safety for a nested object and an array of objects. Specifically, I want the 'name' property to correspond to the key of the respective object it belongs to. For instance, in the scenario ...

Dropzone ceased functioning following the transition from version "4.2.0" to "5.7.0" while utilizing jquery version "3.3.1"

Currently, I am loading my libraries in the following way: <link href="~/lib/dropzone/dropzone.min.css" rel="stylesheet" /> <script src="~/lib/dropzone/dropzone.min.js"></script> <script src="~/Scripts/jquery-3.3.1.min.js"></sc ...

Is this filter selector in jQuery correct?

It appears to function correctly, but I am unsure if there is room for improvement. I aim to target any HTML element with a class of edit-text-NUM or edit-html-NUM and adjust its color. This is the code snippet I am currently utilizing... jQuery(document ...

Tips for detecting when a browser is closing in a web application that is integrated with a master page

Currently, I am working on a web application that uses a master page. I need to be able to detect when the user is closing the browser so that I can raise an event to clean up session variables. I attempted using the unload JavaScript event, but it seems ...

What is holding Firestore back from advancing while Firebase Realtime Database continues to evolve?

I am currently working on a chat application using Firebase within my Vue.js project. In this setup, I need to display the user's status as either active or inactive. To achieve this, I implemented the solution provided by Firebase at https://firebase ...

Exploring the power of Cucumber, Ruby, Capybara, and Selenium: Enhancing the 'visit' method to handle dynamic content delays

For weeks now, I've been dealing with an issue that seems to have no solution found online... like waiting for ajax, etc... Check out the versions of gems: capybara (2.10.1, 2.7.1) selenium-webdriver (3.0.1, 3.0.0) rspec (3.5.0) running ruby 2.2.5 ...

Tips for adding and removing active class with navbar links using JavaScriptonclick

I need help with toggling the "li-active" class on my navigation bar links. Currently, when I click on a link, the "li-active" class is transferred from the previous link to the newly clicked link instead of removing it first. Can someone please assist me ...

Encountered a setback while trying to add information to a MySql database through Express

When I try to execute an insert query on a database, it throws the following error: code: 'ER_PARSE_ERROR', errno: 1064, sqlMessage: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server versio ...

Validation based on the condition of the request body in Express using express-validator

I have a specific route in place for handling different scenarios, with only minor variations in logic between them. To keep things streamlined, I have decided to utilize a single endpoint and differentiate between cases using the parameter 'type&apos ...

Android is now asking for location permissions instead of Bluetooth permissions, which may vary depending on the version

I am currently troubleshooting a React Native application that relies heavily on Bluetooth permissions. However, I am encountering an issue with the Android platform where the Bluetooth permissions are appearing as unavailable. I have configured the permi ...

Ways to permit https://* within a content security policy (CSP) configuration

I'm currently incorporating CSP into my website but encountering an issue with the img-src header. I'm using NodeJS and Express to develop the site for my Discord Bot, and I want to revamp it but I've hit a roadblock. ====== This is the co ...

What is the best approach for scaling @material-ui Skeleton in a grid row with variable heights?

I am working on creating a grid of Avatar images with a transition state where I want to show a skeleton representation of the image. To achieve this, I am using @material-ui/lab/Skeleton. The issue I'm facing is that since my images are set to autos ...

It's important to understand how to correctly send state values from a parent component to a child component

I have a tab menu in my code and I am looking to implement a feature where tabs can be switched using a button. The challenge is passing the values of these tabs into the onclick function of the button in order to navigate between them. Here is an example ...

Angular's asynchronous HTTP request allows for non-blocking operations when

I'm currently working with Angular 6, and I've encountered an issue while updating my resource instance in the following way: this.user = api.getUser(); public getUser(): User { const myHeader = new HttpHeaders({ 'Authorization' ...

Presenting a ui-router modal while maintaining the parent state's refresh-free appearance

I have implemented a unique feature in my angular app called modalStateProvider. It allows me to easily have modals with their own URLs. // Implementing the modalStateProvider app.provider('modalState', [ '$stateProvider', function ...

jQuery interprets every PHP response as having a status of 0

I've been working on a way for javascript to verify the existence of a user in a MySQL database. My method involves using jQuery to send the user details to a PHP script that will then check the database. The data is successfully sent to the PHP scr ...

Generate a sparse array using only a single line of code

Is it possible for JavaScript to create a sparse array similar to what Bash can do in one line? names=([0]="Bob" [1]="Peter" [20]="$USER" [21]="Big Bad John") § Creating Arrays Can JavaScript achieve the same with sparse arrays? ...

Tips for persisting nested arrays of objects data with Mongoose

Currently, I am transmitting data from an angular reactive form. Here is the UI image of the Angular reactive form: Angular reactive form UI image Additionally, here is the image showing the data being sent to the backend in the browser console: Data bein ...

Modify the image source using Javascript

I need to update the src attribute of an image in a parent element nested within a ul li when a link is clicked. Here's my code so far. I know how to use JavaScript to change the src attribute, but I'm not sure how many levels I need to go up to ...

Remove the option to delete without making any changes to the flash file

Utilizing the DataTable javascript tool to export a grid, I have obtained the following HTML generated code: <div class="DTTT_container"> <a class="DTTT_button DTTT_button_copy" id="ToolTables_example_0" tabindex="0" aria-controls="e ...