简体   繁体   English

如何比较输入和JSON数据

[英]How to compare Inputs and JSON data

I'm working on a school project and I need to validate some users without making a real Database. 我正在做一个学校项目,我需要验证一些用户而不创建真实的数据库。 My problem is that when I compare the information entered in the inputs with the information storaged in JSON, it pops an error for every option that doesn't match. 我的问题是,当我将输入中输入的信息与JSON中存储的信息进行比较时,它会为每个不匹配的选项弹出一个错误。 What I want is to reduce the multiple errors into only one (in case that the username or the password doesn't matches with the information storaged in JSON). 我想要的是将多个错误减少为一个(如果用户名或密码与JSON中存储的信息不匹配)。 Here is My JavaScript: 这是我的JavaScript:

 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')); }); 

And here is the fake database made with JSON: 这是用JSON制作的假数据库:

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

Using vanilla JavaScript : 使用原始JavaScript:

 // This is only to simulate your fetch from JSON function fakeFetch () { return Promise.resolve([ {"email": "James", "pwd": "1111"}, {"email": "Peter", "pwd": "2222"}, {"email": "Josh", "pwd": "3333"} ]); } 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 }; fakeFetch() .then( users => { // Check each user in users and try to find a match for ( let user of users ) { // Destructuring email and password from the current user let { email, pwd } = user; // Comparing email and pwd from active user with the ones in object if ( email === object.email && pwd === object.pwd ) { // Found, do something console.log( 'found!' ); return; } } // Not found, do something else console.log( 'Not found...' ); }) .catch(error => console.log( error ) ); }); 
 <form> <input type="text" id="email"/> <input type="test" id="pwd"/> <input type="submit"/> </form> 

I tried explaining in the comments, but its probably easier to show you. 我尝试在评论中进行解释,但可能更容易向您展示。 I think its better to compare the smallest amount of data possible (rather than a big JSON string), like email to email and password to password. 我认为最好比较可能的最小数据量(而不是大的JSON字符串),例如从电子邮件到电子邮件以及从密码到密码。

So I changed your if to do a more simpler compare. 因此,我更改了您if进行更简单的比较。

To condense all your errors into one, you can include a flag and set it to true if a match is found. 要将所有错误汇总为一个,可以包含一个标志,如果找到匹配项,则将其设置为true Then outside the forEach loop you can check that flag and log just 1 error (if there is no match) 然后在forEach循环之外,您可以检查该标志并仅记录1个错误(如果没有匹配项)

 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!"); } 

The main idea of your function is to, given a tuple (username, password), check if it exists in your database, which is an array of objects in this case. 函数的主要思想是给定一个元组(用户名,密码),检查它是否存在于数据库中(在这种情况下为对象数组)。 You could say you want to filter from the array the entries whose username and password match what was inserted by the user. 您可能会说您想从数组中过滤用户名和密码与用户插入的内容匹配的条目。 Since there should be no repeated tuples of username/password, your filter should either return the matching tuple or null. 由于应该没有重复的用户名/密码元组,因此您的过滤器应返回匹配的元组或为null。

An approach for this could be the following: 为此,可以采用以下方法:

 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 way the code shows what you are trying to accomplish and does it with no side effects. 这样,代码可以显示您要完成的工作,并且没有副作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM