Check if object key value exists, if so get another key value - javascript

How do I check if the "username" is equal to "name" and if it is the get the "id"?
So I'm trying to check if a name exists, if it does, then get the id.
var name="Lisa";
var users = [
{ id:"1234", username:"Claes", room: "General" },
{ id:"5678", username:"Lisa", room: "General" }
];
I have tried with this, but I don´t know what I´m missing?
for (username in users) {
if (!users.hasOwnProperty(username)) continue;
if (users[username]=name) {
nameexists = true;
id = users[id];
console.log('user exists'+users[id]);
}else{
nameexists = false;
console.log('user does not exist');
}
}
Any input really appreciated, thanks.

In Javascript, the syntax for (username in users) { .. is used to iterate the properties of an object, not an array.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
To iterate an array use normal for, the Array's forEach method or the for..of syntax (ES6)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array and https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of
Simple solution:
users.forEach(function(user) {
if (user.username) { // note this will expect a 'truthy' value i.e. except for false, 0, "", null, undefined, and NaN
nameexists = true;
id = user.id;
console.log('user exists'+user.id);
} else {
nameexists = false;
console.log('user does not exist');
}
}
BTW: checking equality uses '==' or '===', not '='.

Related

I need a way to break this loop or an alternative way to do this

I'm new to js and firebase. I'm trying to use firebase database for a custom login by using my own table called users. I have used a for each loop to go through the data. But the else part is executed multiple time because of this. I need to break the loop so it won't happen.
This is my data:-
{"users" : [ {
"userId" : "1",
"username" : "admin",
"password" : "admin",
"type" : "admin"
}, {
"userId" : "2",
"username" : "cashier",
"password" : "cashier",
"type" : "cashier"
}]
}**
This is the code I wrote:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
var error=false;
firebase.database().ref('users').orderByKey().once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var users = childSnapshot.child('username').val();
var pass=childSnapshot.child('password').val();
if(txtuser==users && txtpass==pass){
var type=childSnapshot.child('type').val();
if(type=="admin"){
location.href="admin.html";
}
else if(type=="cashier"){
location.href="cashier.html";
}
}
else{
error=true;
}
});
});
if(error==true)
{
window.alert("Invalid Credentials");
location.href="index.html";
}
}
Password Authentication
Instead of using your method of storing authentication details in the database, use the Sign in a user with an email address and password flow.
However, because you are using usernames not emails, append your storage bucket domain to the username (which will normally be PROJECT_ID.appspot.com).
So your "admin" and "cashier" users would become "admin#PROJECT_ID.appspot.com" and "cashier#PROJECT_ID.appspot.com". For the sake of email authentication, these are valid email addresses, even though they don't have inboxes.
You can then use firebase.auth() across your web app to manage your user's access control to pages like "admin.html" and "cashier.html".
Note: If you ever send out email to your users, make sure to omit emails that match "*#PROJECT_ID.appspot.com"
Answering the question
WARNING: Do not authenticate this way. Please use above method.
Passwords should never be stored in plain text
Passwords should never be stored in plain text
Users should never have access to another user's credentials in any database
For the sake of answering the question, you could use the following code:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
firebase.database().ref('users').orderByChild('username').equalTo(txtuser).once('value')
.then(function(snapshot) {
if (!snapshot.hasChildren()) {
throw "username not found";
} else if (snapshot.numChildren() != 1) {
throw "duplicate usernames";
}
// only one child at this point, so only called once
snapshot.forEach(function(childSnapshot) {
if (pass != childSnapshot.child('password').val()) {
throw "password mismatch";
}
var type=childSnapshot.child('type').val();
if(type=="admin") {
location.href = "admin.html";
} else if(type=="cashier") {
location.href = "cashier.html";
} else {
throw "unknown user type";
}
})
})
.catch(function(error) { // catches any errors thrown by promises
location.href = "index.html";
});
}
In the above code, each throw is caught by the Promise returned by the Firebase query. You can read up on Promises here.
Just check if error is set to true inside the .forEach and use return to "break" out:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
var error=false;
firebase.database().ref('users').orderByKey().once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var users, pass;
if (error) { return; } // <-- "break" the "loop"
users = childSnapshot.child('username').val();
pass = childSnapshot.child('password').val();
if(txtuser == users && txtpass == pass){
var type=childSnapshot.child('type').val();
if(type == "admin"){
location.href="admin.html";
}
else if(type == "cashier"){
location.href="cashier.html";
}
} else {
error = true;
}
});
if(error) {
window.alert("Invalid Credentials");
location.href="index.html";
}
});
}

Skip to else if property is undefined

I have function that creates a team and puts data to database. Now I'm trying to check if team already exists, if it does exists then reply with message. I have problem with my if statement.
if (result[0].teamname == teamName)
When result[0].teamname is undefined it shows Cannot read property 'teamname' of undefined it ignores else and throws an error. How can I make so that does not ignore else?
Here is the function I use to create team.
function createTeam(teamName, members, message) {
teamName = teamName.replace("_", " ");
let insertTeam = `INSERT INTO teams (teamname) VALUES ('${teamName}');`;
db.select(`SELECT id_t, teamname FROM teams WHERE teamname = '${teamName}'`, function(err, result) {
if (err) {
throw err;
} else {
if (result[0].teamname == teamName) {
if (message.guild !== null) message.delete();
message.reply("this team already exists!");
} else {
db.query(insertTeam);
db.select(`SELECT id_t FROM teams WHERE teamname = '${teamName}'`, function(err, result) {
if (err) {
throw err;
} else {
for (let i = 0; i < members.length; i++) db.query(`INSERT INTO team_user (user, team) VALUES ('${members[i]}' , ${result[0].id_t})`);
}
});
if (message.guild !== null) message.delete();
let newTeam = new Discord.RichEmbed()
.setThumbnail("https://cdn.discordapp.com/emojis/542789472421675028.png?v=1")
.setColor("#15f153")
.addField("New team has been created!", `Team ${teamName} has been created with total of ${members.length} members!\nGood luck!`);
message.channel.send(newTeam);
}
}
});
What have I tried so far:
Checking if result[0].teamname is undefined
Checking if result length is not 0
try-catch statement
if (result[0] && result[0].teamname == teamName)
First of all you need to check if result[0] is not undefined
You need to short-circuit the condition. All this means is you want to first check that result exists before checking properties of result
So for example, your code should look like this:
if (result && result[0] && result[0].teamname == teamName) {
//Do something
}
If result is array with more then one value, then you need to iterate over every one of them, you can use filter array method for this:
var found = result.filter((row) => row.teamname == teamName);
if (found.length) {
}
You can also as #ThomasKleßen mention in comment check if result is not undefined:
var found = result && result.filter((row) => row.teamname == teamName).length;
if (found) {
}
You can always do a default value
if ((result || [{}])[0].teamname == teamName)
If the result is falsy, it will default to an array of an empty object, which will allow for the array access and dot notation to work, but the equality to fail.

Searching in object inside array

I'm trying to hardcode a kind of log in system, for that i was trying to have two inputs and on click check if those values matched the ones in the array, the array having two objects for two possible answers…
Well, i cant get it to work, all of the suden my variables are not recognized and the overall code has gone kaput… here is the Pen
thanks in advance!
the code so far btw
$(".submit").click(function() {
//bidimensional array
var data = [{
user: "cinco",
pw: "king"
}, {
user: "manco",
pw: "wawa"
}];
var name = $(".name").val();
var pass = $(".pw").val();
if (data.user.includes(name) && data.pw.includes(pass)) {
$(".check-input").addClass('valid');
} else {
$(".check-input").addClass('invalid');
}
});
$(".input").focus(function() {
$(".check-input").removeClass("valid");
$(".check-input").removeClass("invalid");
});
You can use find() like this
if (data.find(v => v.user === name && v.pw === pass)) { ... }
Please note that using javascript as your login is highly insecure as everybody can just open the console and read the credentials.
For your comment, the => is part of an arrow function, it boils down to
if (data.find(function(v) {
return v.user === name && v.pw === pass;
})) { ... }
var data = [{
user: "cinco",
pw: "king"
}, {
user: "manco",
pw: "wawa"
}];
checkLogin(usr, pwd){
for(var index in data) {
var obj = data[index];
if(obj.user == usr && obj.pw == pwd) {
return true;
}
}
return false;
}
checkLogin('chino', 'wrongPwd'); // returns false
checkLogin('chino', 'king'); // returns true
You need to access the individual objects in the array and get the user and pw properties of those objects. The array itself doesn't have those properties.
Here's a working version that also streamlines your code:
$(".submit").click(function() {
// This is not a bidimensional array. It's just an array of objects
var data = [{
user: "cinco",
pw: "king"
}, {
user: "manco",
pw: "wawa"
}];
var name = $(".name").val();
var pass = $(".pw").val();
// You need to access the individual objects in the array and get
// the user and pw properties of those objects. The array itself
// doesn't have those properties.
// Loop through the array and check each object
// You can't return from a forEach loop, so we'll set up a variable
// that will be used after the loop is complete
var valid = false;
data.forEach(function(obj){
// Don't check for inclusion of the data, check for exact match
if (obj.user === name && obj.pw === pass) {
valid = true;
}
});
// Now that the loop is done, set the validity
$(".check-input").addClass(valid ? 'valid' : 'invalid');
});
$(".input").focus(function() {
$(".check-input").removeClass("valid");
$(".check-input").removeClass("invalid");
});
.check-input{
width:250px;
height:40px;
background-color:gray;
}
.valid{
background-color:green;
}
.invalid{
background-color:crimson;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input name">
<input type="text" class="input pw">
<button class="submit">Submit</button>
<div class="check-input"></div>

Firebase web. Checking if an object in an array has a particular value

Im trying to compute if an array has a particular object that has a value which matches to what I want
The array is membersArray and here is where it comes from
<firebase-query
id="querymembers"
path="/members"
order-by-child="crew"
equal-to="[[routeData.key]]"
data="{{membersArray}}">
</firebase-query>
The property
_isUserAMember: {
type: Boolean,
computed: '_computeIfIsMember(membersArray,user)'
},
And the function itself
_computeIfIsMember: function(membersArray, user) {
if(user && membersArray) {
// var found = false;
// for(var i = 0; i < membersArray.length; i++) {
// if (membersArray[i].userid === user.uid) {
// found = true;
// break;
// }
// }
// return console.log(found);
return console.log(membersArray.some(function(el) {
return el.crew === username;
}));
}
},
I keep getting false. What could I be doing wrong ?
This is how the members path looks like
console.log(typeof(this.membersArray)); // object
Assuming that firebase query will only return a result if the user.uid equal-to the child, I don't think you need to recheck the result.

add a condition while inserting data in mongodb

Basicly I want to check if a specific data exists in the database before inserting data(im using native mongodb driver), so what I tried is using collection.findOne() to check if data exists, if the property of the attribute is null the collection.insert() performs.
Apparently my code is not working according the logic, please someone enlighten me!
some of my code:
exports.addUser = function(req, res) {
var twitterId = req.body.provider;
var userEmail = req.body.email;
db.collection('users', function(err, collection) {
collection.findOne({'email':userEmail }, function(err, item){
if(item.email === null){
collection.insert({
'email': userEmail,
'provider': {
'twitter': {
'id': twitterId
}
}
}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
}else{
console.log("Email exits ");
}
});
});
}
Your if statement is expecting item.email to be explicitly set to null. If item.email is not a property of item, that if statement will evaluate to false.
var foo = {bar:'baz'}
foo.bar // 'baz'
foo.notSet // undefined
foo.notSet === undefined // true
foo.notSet === null // false
// now if we set foo.notSet to undefined...
foo.notSet = null // undefined
foo.notSet === null // true
So, there are few options...
if (item.email) {} else {};
if ('email' in item) {} else {};
if (item.hasOwnProperty('email')) {} else {};
If you try and call a property that does not exist on the object itself, JS will check it's prototype, if it doesn't exist on the prototype anywhere, then it will return undefined.
The in operator will check to see if the left side operand is a property of the right side object.
Finally Object.hasOwnProperty will check for it's argument as a property on the object.
All that to say, {upsert:true} would probably be your best bet.

Categories