Exploring the differences between arrays and objects provided by users

I am working on a functionality that involves comparing user input with predefined usernames and passwords. Here is what I have so far:

var sys = {
    users: [
        {user: 'user1',  pass: 'qwerty'},
        {user: 'Ragnar',  pass: 'lothbrok'},
        {user: 'guest',  pass: 'guest'}
    ],
    valid: function(){
        var userInp = document.getElementById("userInp").value;
        // var pwInp = document.getElementById("pwInp").value;
        var check = false;
        for (var i=0; i < sys.users.length; i++ ){
            if (userInp == sys.users.user /*&& apwInp == 'sys.users{pass}'*/) {
              alert ("logged in")
            } else {
               alert ("no match")
            }
        }
    }

}

I am determined to make it work in this specific way, but I am facing some challenges with it.

Answer №1

To ensure clarity in your code, it's recommended to keep your username-password combination as a separate object and handle authentication in a distinct block of code.

    //username-password objects
    var sys = {
    users: [
        {user: 'user1',  pass: 'qwerty'},
        {user: 'Ragnar',  pass: 'lothbrok'},
        {user: 'guest',  pass: 'guest'}
    ]}

    //retrieve user inputs and store them in variables
    var username = document.getElementById("userInp").value;
    var password= document.getElementById("passInp").value;
    var count = 0;
    for(i = 0; i< sys.users.length; i++)
    {
        if(sys.users[i].user == username && sys.users[i].pass == password)
            count++;
    }

    if(count>0)
        alert("correct credentials");
    else
        alert("incorrect credentials");

Your code is already quite clear, but separating the authentication logic can make it even more organized. Hope this additional tip helps!

Answer №2

Utilize Array::some method

var system = {
    users: [
        {
            user: 'JohnDoe',
            pass: 'password123'
        },
        {
            user: 'JaneSmith',
            pass: 'securePassword'
        },
        {
            user: 'admin',
            pass: 'admin'
        }
    ],
    validateUser: function () {
        let username = "JaneSmith";
        let password = "securePassword";
        return system.users.some(u => u.user === username && u.pass === password);
    }
}

console.log(system.validateUser())

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

What could be the reason for the data showing up only within a foreach loop but turning into a non-object outside of it?

I am a beginner in PHP and feeling confused about a certain aspect... When I use the following code, it displays the data: <?php foreach ($profile as $p):?> <?php echo $profile->custom_url;?> <?php endforeach?> ...

Service Worker error - Received redirected response when RedirectMode is not set to "follow"

Browser: Firefox 58.0.2 (64-bit) I am attempting to create a very basic service worker to store content for offline viewing, following the guidelines provided here and here. After installing the service worker successfully upon loading the page for the f ...

Adding negative values to the Tailwind CSS utility plugin is a simple process that can greatly enhance

Adding Negative Values to Tailwind CSS Utility Plugin Quick Summary: I've developed a custom Tailwind utility plugin that includes numeric values. I'm looking for a way to introduce negative numbers by adding a - at the start of the class, simi ...

Show a caution message when there has been no activity on the page for 3 minutes

I am currently developing a PHP page that includes timed tests. The maximum duration for a test is 1 hour, however the session times out after just 10 minutes of inactivity. Interestingly, when the timeout occurs, the test page does not automatically refre ...

Improving a Vue.js notification component with data retrieved from a fetch request result

Struggling with updating the content inside a vuetify v-alert. There's an issue when trying to update Vue component properties within the sessionID.then() block after logging into a system and receiving a session id. Vue.component('query-status ...

A quicker method for setting the emitted value to data

Is there a way to pass data from child to parent without creating a method for assigning the value? I want to be able to assign it directly in the template. This is my current code: Child <h1 @click="$emit('title', 'Home')&quo ...

Deactivate a button on a specific tab

My setup includes two tabs: <div class="modal-body"> <form name="myForm" novalidate="novalidate"> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#basicInfo">Info</a></li> ...

Continuously flowing chain of replies from a series of queries using RxJS

I am exploring the world of RxJS and seeking guidance from experienced individuals. My goal is to establish a synchronized flow of responses, along with their corresponding requests, from a stream of payload data. The desired approach involves sending ea ...

Guide to manipulating DOM elements with Angular.js: inserting or deleting elements using createElement

Within my Angular directive, I am dynamically generating an external script from the DOM for a specific object within a list. This script includes both a 'script' tag and div content. While I am able to successfully add the script, I am encounter ...

Performing a test on API GET Request with Playwright

I've been attempting to verify the GET status using this particular piece of code. Regrettably, I keep encountering an error message stating "apiRequestContext.get: connect ECONNREFUSED ::1:8080". If anyone has any insights or suggestions on how to re ...

Guide on using axios in vue.js to interact with the API

I need help with a functionality on my website where users can select a car brand from a list of radio buttons. After selecting a brand, I want to retrieve an array of models from the server and display them on a new page. Can someone guide me on what spec ...

The listener is not activating the AJAX function

It seems like the function validate() is not being called in the listener, causing an error and preventing data from being added to the database. Here is the code snippet from index.php: <!DOCTYPE html> <html> <head> <title>< ...

Using Javascript/HTML to enable file uploads in Rails

I'm currently facing an issue with uploading and parsing a file in Rails, as well as displaying the file content in a sortable table. I followed a tutorial on to get started. This is what my index.html.erb View file looks like: <%= form_tag impo ...

The AJAX file retrieval function is not functioning

I'm working on downloading a file using ajax, but I seem to be facing an issue. Can anyone help me figure out what's going wrong with the code below? url = "https://firebasestorage.googleapis.com/v0/b/analyst-3206a.appspot.com/o/research_reports ...

Change the height of textarea dynamically using jQuery

I am trying to create a comment box similar to Facebook's, where it resizes as text fills it using Expanding Text Areas Made Elegant This is how my view looks: <div class='expandingArea'> <pre><span></span></ ...

Ways to resolve the error "Expected an assignment or function call but found an expression with no-unused-expressions"

Issue : Error in ./src/components/main.js Line 7: No function call or assignment found, only an expression is present (no-unused-expressions) Search for the specific keywords to get more information on each error. import React from 'react'; ...

Require assistance in accessing the second tab on a webpage using JavaScript tabs

Currently, I have a web page with two tabs that are initially hidden until the corresponding tab button is clicked. The click event is managed by jQuery. For example, let's assume that tab 1 is the default one when the page loads. Now, I am looking fo ...

Issue with parsing JSON data for heatmap in Mapbox

Here's the code I'm using: heat = L.heatLayer([], { maxZoom: 12 }).addTo(map); $.getJSON("js/example-single.geojson", function(data) { var geojsosn = L.geoJson(data, { onEachFeature: function (feature, layer) { console.log(f ...

Having trouble loading an image after successfully connecting to an API with react.js

I've been working on a custom fetch component to load images from the "the dog API" onto my page. However, I'm facing some issues with getting the images to display correctly. Can anyone spot what might be missing in my setup? App.js import &apo ...

How can I effectively develop a versatile user interface for a website using Ruby on Rails that is compatible with all

Currently, I am in the midst of developing a web application using Ruby on Rails. Occasionally, I encounter challenges with cross-browser compatibility when it comes to CSS and Javascript. Are there any strategies you recommend to reduce these issues dur ...