Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
pull out data from array in localStorage

I have a function that takes data from an input and saves it as data in an array during registration. Now I want another function to check during login if the data exists and if it matches. How can I do this using javascript only? In short, I need a function that checks if the data entered by the user exists and if so, logs him in.

function saveData() {
  let name, email, password;
  name = document.getElementById("username").value;
  email = document.getElementById("email").value;
  password = document.getElementById("password").value;

  let user_records = new Array();
  user_records = JSON.parse(localStorage.getItem("users"))
    ? JSON.parse(localStorage.getItem("users"))
    : [];
  if (
    user_records.some((v) => {
      return v.email == email;
    })
  ) {
    alert("Email wykorzystany");
  } else {
    user_records.push({
      name: name,
      email: email,
      password: password,
    });
    localStorage.setItem("users", JSON.stringify(user_records));
  }
}

I know that this is not how registration should be done. I am just doing it to learn new things.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

function saveAndTestUser() {
  // here use const as they are not updated
  const name = document.getElementById("username").value;
  const email = document.getElementById("email").value;
  const password = document.getElementById("password").value;

  // Get all the records of the users
  // prefer camelcase : not a rule though but it's better this way
  const storedUsers = localStorage.getItem('users')

  // if there are no stored users then assign empty array 
  // so that we don't get unexpected errors
  const userRecords = storedUsers ? JSON.parse(storedUsers): []

  // Checking if email already exists
  if(userRecords.some(user => user.email === email)){
    alert("user already exists")
    return false; // stops the function execution
  }
  
  // If email doesn't exists then the code below will be executed
  // Similar to if-else
  // Add current record to existing records
  const newRecords = [...storedUsers, {name, email, password}] 

  // Set the new record to storage
  localStorage.setItem("users", JSON.stringify(newRecords));
 
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

this is a basic login, when you verify that the emmail and password are right, you can do wathever you want

function checkData() {
        const name = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        let user_records = JSON.parse(localStorage.getItem('users')) || [];

        if (
          user_records.find((user) => {
            return user.name == name && user.password == password;
          })
        ) {
          alert('Logged in');
          // do your things here
        } else {
            alert('wrong email or password');
          // do your things here
        }
      }
<input id="username" />
    <input id="password" />
    <input type="submit" value="submit" onClick="checkData()" />

Extra: This is a thing that you can do only for learning purpose, wich is to add a key to the local storage, for example: localStorage.setItem('loggedIn', true) and set in every page a check for this value, if is true show the page, if is false redirect to login. In the real world we use JWT tokens that contains all the information about the user etc... You can search for JWT token authentication on google and learn that, wich is really usefull in the front-end world

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda