Comparing inputs to JSON data: A comprehensive guide

For a school project, I am trying to validate users without the use of a real database. However, I am facing an issue where every mismatch in information entered is resulting in multiple errors. What I am aiming for is to consolidate these errors into just one notification (in case either the username or password does not match the stored JSON data). Below is the JavaScript code I am using:

const form = document.querySelector('form');
form.addEventListener('submit', function(e){
e.preventDefault();
    
    const emailInput = document.querySelector('#email').value;
const pwdInput = document.querySelector('#pwd').value;

const object = {
email: emailInput,
pwd: pwdInput
};

fetch('users.json')
  .then(res => res.json())
.then(data => {
data.forEach(function(user) {

const userInfo = JSON.stringify(user);
const databaseInfo = JSON.stringify(object);

if(userInfo === databaseInfo) {
console.log('success');
} else {
console.log('err');
}

});
})

.catch(error => console.log('error'));

});

Below is the JSON structure of the fake database:

     [
      {"email": "James", "pwd": "1111"},
      {"email": "Peter", "pwd": "2222"},
      {"email": "Josh", "pwd": "3333"}
     ]

Answer №1

Utilizing pure JavaScript :

// Simulating fetching data from JSON using a fake function
function simulateFetch () 
{
  return Promise.resolve([
    {"email": "Alice", "pwd": "1234"},
    {"email": "Bob", "pwd": "5678"},
    {"email": "Charlie", "pwd": "9012"}
  ]);
}

const form = document.querySelector('form');

form.addEventListener( 'submit', function(e){
  e.preventDefault();
    
  const emailInput = document.querySelector('#email').value;
  const pwdInput = document.querySelector('#pwd').value;

  const inputObject = {
    email: emailInput,
    pwd: pwdInput
  };

  simulateFetch()     
  .then( users => {
   
    // Iterate over each user to find a match
    for ( let user of users )
    {
      // Destructure email and password from the current user
      let { email, pwd } = user;
      
      // Compare email and password with the ones in the input object
      if ( email === inputObject.email && pwd === inputObject.pwd )
      {
        // Match found, perform actions
        console.log( 'Match found!' );
        return;
      }
    }
    
    // No match found, perform other actions
    console.log( 'No match found...' );
    
  })
  .catch(error => console.log( error ) );

});
<form>
  <input type="text" id="email"/>
  <input type="test" id="pwd"/>
  <input type="submit"/> 
</form>

Answer №2

Trying to illustrate in the comments was a bit complex, so I figured demonstrating would be more effective. Instead of comparing a large JSON string, I believe it's best to compare the smallest amount of data possible - like email to email and password to password.

Therefore, I modified your if statement to make the comparison simpler.

To consolidate all the errors into one, you can implement a flag and set it to true if a match is detected. Then after the forEach loop, you can check that flag and log just one error (in case there is no match).

var users = [{
  email: "user1",
  pwd: "pass1"
}, {
  email: "user2",
  pwd: "pass2"
}];

var object = {
  email: "user3",
  pwd: "pass3"
};

var isMatch = false;
users.forEach(function(user) {
  if (user.email === object.email && user.pwd === object.pwd) {
    console.log("success");
    isMatch = true;
  }
});

if (!isMatch) {
  // only logs once even though there are multiple users
  console.log("No Match!");
}

Answer №3

The primary objective of the function is to validate a tuple (username, password) by checking if it exists within the database, which is an array of objects in this scenario. The goal is to filter out entries from the array that have matching username and password inputs provided by the user. Since there should not be any duplicate tuples of username/password pairs, the filtering process should either return the matching tuple or null.

One potential approach to achieve this is as follows:

function verifyLogin(loginObject) {
  return new Promise((resolve, reject) => {
    fetch('users.json')
      .then(res => res.json())
      .then(data => data.filter(entry => entry.email ===
loginObject.email && loginObject.pwd === object.pwd).length > 0 ? resolve(true) : resolve(false))

      .catch(error => reject(error));

  });
})

}

verifyLogin(loginObject)
  .then(result => result === true ? console.log('Login successful!') : console.log('Login failed'))
  .catch(error => console.log(error))

This implementation clearly demonstrates the intended functionality without causing any unintended side effects.

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

Using HTML to format Microsoft Teams cards

What I have are Microsoft Teams chat messages obtained through an API that I wish to showcase on a website. The issue arises when these chat messages contain JSONs of cards. I attempted to display adaptive cards using the Adaptive Card JS SDK, and it succe ...

How can I pass a JSON object from CefSharp's ChromiumWebBrowser to JavaScript without converting it to a string?

browser.JavascriptObjectRepository.Register("BrowerFunc", new BrowerFunc(), isAsync: false, options: bo); public class BrowerFunc { public string readIniData(string Section, string iniFilePath) { string Conte ...

Tips for populating two select tags with jQuery AJAX using a JSON document

Looking for help with my HTML code that includes two select tags. I want to use AJAX to populate the 'collegeselect' based on the selection in the 'departmentselect'. HTML CODE titled 'collegedepartment.html' <html> ...

Having trouble with Typescript compiler "cannot find module" error when trying to use Webpack require for CSS or image assets?

Currently, I am working with vanilla Javascript and utilizing the Typescript compiler's checkJs option for type checking in VSCode. My Webpack configuration is properly set up to handle various asset types such as CSS and images during builds. However ...

PHP-powered Countdown Timer for triggering a button's action

Hey everyone, I could use some assistance. Here's my situation - I have a database table with a column called "created_time" that stores the current system time in HH:MM AM/PM format. I want to have a button on one of my PHP pages named "Start Exam" t ...

Having trouble implementing a method to shift elements in an array using Array.Copy. I need to come up with a better solution

Task - Develop a function called Shift that shifts the elements of an array based on given shift instructions. The function should use for loops, array indices, and Array.Copy method to copy array elements. It takes two arguments: source (the array of inte ...

What are the steps to execute a file on localhost using an HTML page?

Currently, I have an HTML file that leverages the Google Calendar API javascript to read the next event on my calendar. The functionality works flawlessly when manually inserting a specific URL in a browser address window, which triggers a GET request in a ...

Leverage the power of jq to access values within nested

Today, I came across a file named heroes.json. Inside this file, there is a nested array of objects called superpowers: [ { "hero": "Superman", "id": "123", "realName": "Clark Kent", ...

Accessing arrays with multiple dimensions in C

Understanding that multidimensional arrays are allocated contiguously, the declaration int[4][3] arr; will allocate 12 int cells in a sequential manner. I have two questions regarding this: first, considering C does not store array lengths, how does it ca ...

Purpose of triggering another function during an ajax request

I have encountered an issue while working on a project. There is a page with an input field called balance within a div named balanceDiv. This field should not be visible to the admin, so I used ng-show to hide/show the div based on the user's login I ...

What causes phaser to flicker on mobile devices?

I am currently working on developing a game for both desktop and mobile platforms using phaser. However, I have encountered an issue when testing it on mobile devices - the game flashes frequently and becomes barely playable. For reference, you can access ...

Unresolved commitment within MongoDB

let comments = await Comment.find({ post }) .populate({ path: "user", select: "name photoURL role page" }) .sort({ createdAt: -1 }); console.log("comments --", comments); const pages = []; let pagesDat ...

Guide to migrating disk.db in sails.js to a MongoDB database

Currently, I have a node.js application built with the sails.js web framework. During development, I am using the sails-disk adapter and the sample data from disk.db looks like this: { "data": { "authentication": [ { ...

Tips for organizing a JSON object's keys into separate arrays while eliminating any duplicates

Take the JSON data provided and group it by keys, creating an array of unique values for each key (excluding duplicates). var people = [ {sex:"Male", name:"Jeff"}, {sex:"Female", name:"Megan"}, {sex:"Male", name:"Taylor"}, {sex:"Female", na ...

What are some strategies for retrieving a greater quantity of data from the Stack Exchange API?

When using the Stack Exchange API, only 30 items are returned per request. To retrieve 4500 records, I utilized a for loop as shown below: import requests complete_data=[] for i in range (150): response = requests.get("https://api.stackexchange.com/2. ...

Ajax versus embedding data directly into the HTML code

Currently, my project involves a combination of JavaScript with jQuery and communication with a Django backend. Some aspects of the user interface require Ajax due to the fact that data to be sent is dependent on user input. On the other hand, there is c ...

Enhancing efficiency in fast browser communication using Selenium/Puppeteer

I am seeking to develop a script capable of interacting with webpages with minimal delay, excluding network delays. This script will be utilized for arbitrage trading, so any advice in this realm is appreciated. My current strategy involves using Selenium ...

Explore the array by locating elements based on the initial two letters of each word in the array

In the given array, I am looking to find the first letters in multiple words within the same matrix. It should search through each word and return in an array if found. For example: const data= [ "the lions of teranga", "tiger ...

Ways to enable asset sharing among various Angular.js applications on separate servers

Hello everyone, I am fairly new to the world of Angular.js and currently exploring its potential for our upcoming project. I am curious if anyone has experience with creating multiple Angular.js applications that are hosted on different servers (most li ...

What is the best way to record and share a video with jquery and laravel?

Is there a way to grant users access to record videos within an application and then upload them after previewing? I've been able to successfully record and download a video, but now I'm unsure of how to proceed with uploading it to the server. ...