forEach looping for object in array [duplicate] - javascript

This question already has answers here:
Function with forEach returns undefined even with return statement
(5 answers)
Closed 2 years ago.
database = [
{
username: 'mutho',
password: 'muth',
},
{
username: 'pica',
password: '1234',
},
{
username: 'rudy',
password: '1235'
}
];
news = [
{
username: 'sarah',
timeline: 'Hellow',
},
{
username: 'ingrid',
timeline: 'hello world'
},
{
username: 'rudy',
timeline: 'secret',
}
];
function isvalid(user, pass) {
database.forEach(function (item, index) {
if (item.username === user && item.password === pass) {
return true;
}
return false;
});
}
function signIn(user, pass) {
if (isvalid(user, pass) === true) {
console.log(news);
}
else {
alert("Your Username and password wrong");
}
}
var userprompt = prompt("Input your username : ");
var passprompt = prompt("Input your password : ");
signIn(userprompt, passprompt)
I have some problem, I want to show news is the user and password are right in the database. but when I run this program, it always showing "Your Username and password wrong". what should I do?
thank you for the helping

You need Array#some and return the result of this method.
function isvalid(user, pass) {
return database.some(function(item, index) {
return item.username === user && item.password === pass;
});
}
function signIn(user, pass) {
if (isvalid(user, pass)) {
console.log(news);
} else {
alert("Your Username and password wrong");
}
}
var database = [{ username: 'mutho', password: 'muth' }, { username: 'pica', password: '1234' }, { username: 'rudy', password: '1235' }],
news = [{ username: 'sarah', timeline: 'Hellow' }, { username: 'ingrid', timeline: 'hello world' }, { username: 'rudy', timeline: 'secret' }],
userprompt = prompt("Input your username:"),
passprompt = prompt("Input your password:");
signIn(userprompt, passprompt);

Maybe you re looking for something like this:
function findValidUsers(user, pass) {
return database.filter(item => item.username === user && item.password === pass)
}
where findValidUsers will return a array of all users in your database array that have the same username and password.
e.g:
findValidUser('mutho','muth')
would return {username: 'mutho', password: 'muth'}

Your return true does NOT break your loop, it just ends your callback.
See this: Short circuit Array.forEach like calling break.
Or that: https://stackoverflow.com/a/6260865/3872061.
It might help you understand where your problem lies.

foreach doesn't return any value (or break and early return).
Use a standard for loop.
Example https://stackoverflow.com/a/35450142/3327009
Also, the way you have done it now it will just check your first object in the array (if you translate to a for loop)
You need something like this
var i
for (i=0; i<database.length;i++)
if(foobar)
return true
return false

Related

Storing the name of the current user and matched user in state using useEffect returning incorrect output

I have a function in my context that takes in two data points, the current username and the username of a randomly selected user who is online
const pairProgrammingMatching = (username, matchedUser) => {
setPairUsers({username: matchedUser })
}
I call this function in another component using useEffect()
useEffect((() => {
console.log('curr username is', username)
pairProgrammingMatching(username, checkOnlineUsers(pickRandom()).username)
console.log('inside pairUsers state', pairUsers)
}), [])
checkOnlineUsers simply returns a list of all users who are currently online and active
let checkOnlineUsers = () => {
const results = onlineUsers.filter(obj => {
return obj.profile.is_online === true && obj.profile.currently_active === false && obj.username !== user.username
})
return results
}
Here's a sample of what this function returns
[{ email: "***#gmail.com"
first_name: ""
last_name: ""
profile: {city: 'Washington DC', country: 'USA', is_online: true, currently_active: false}
username: "testingUser" }]
pickRandom simply picks a number between 0 and n, with n being the number of users returned in checkOnlineUsers:
const pickRandom = () => {
return Math.round(Math.random()*onlineUsers.length)
}
The problem here is that if I print out pairUsers inside my useEffect I expect to see this:
{ 'userA': 'testingUser' }
with userA being the name of the current user. However this is what I get:
{username: undefined}

How to access array elements that are defined in another array of Mongoose scheme object Array?

This is the User schema in mongoose:
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
},
name: {
type: String,
required: true,
},
Addtasks: [
{
topic: String,
words: Number,
keywords: String,
website: String,
otherdetails: String,
exampleRadios: String,
deadline: Date,
Date: String,
fileName: String,
Bigpaths: [],
},
],
});
module.exports = mongoose.model('User', userSchema);
I want to use/access the Bigpaths array, which is defined inside the Addtasks array, which is defined in User. Data is already are there in mongoDB, which I have inserted via UI page. I am trying the following code but I am getting this error in console:
data.Addtasks[Object.keys(data.Addtasks).length - 2].Bigpaths.forEach(
(element) => {
// ...
}
)
as
TypeError: Cannot read property 'Bigpaths' of undefined
at \Desktop\grumpytext\routes\index.js:99:71
Code:
const { files } = req;
User.findOne({ email: req.user.email }, function (error, data) {
if (error) {
console.log('Three');
} else if (data) {
if (Object.keys(data.Addtasks).length > 1) {
data.Addtasks[Object.keys(data.Addtasks).length - 2].Bigpaths.forEach(
(element) => {
files.forEach((currentElement) => {
if (element.name == currentElement.filename) {
files.pull(currentElement.filename);
}
});
}
);
}
}
});
How to resolve this error or how to access all the elements of Bigpaths array so that I can iterate it with forEach loop?
I'm not sure here, but I think you need to populate Addtasks prior to manipulating it:
const files = req.files;
User.findOne({email:req.user.email}).populate('Addtasks').exec((error, data) => {
if (error) {
console.log("Three");
}
else
{
if(data)
{
if(Object.keys(data.Addtasks).length > 1)
{
console.log("Addtasks count: " + Object.keys(data.Addtasks).length);
data.Addtasks[Object.keys(data.Addtasks).length - 2].Bigpaths.forEach(element => {
files.forEach(currentElement => {
if(element.name == currentElement.filename)
{
files.pull(currentElement.filename);
}
})
});
}
}
}
});
Please notice the log console.log("Addtasks count: " + Object.keys(data.Addtasks).length); - in case the solution does not work, I advise to add some prints, especially to check if the count of elements is as expected or properties within an object are fine.

How can I pass parameter correctly?

const root = {
user: (id) => {
console.log("returning object " + JSON.stringify(id.id) + " " + JSON.stringify(storage.select("users", id.id)))
return storage.select("users", id.id)
}
}
I want to call the arrow function in root.user but I think I can't pass the parameter correctly, so I tried this --> let user = root.user('101')
and on the console I got this -->
returning object undefined
[{"firstName":"Gokhan","lastName":"Coskun","login":"gcoskun","id":101}]
{"firstName":"George","lastName":"Clooney","login":"gclooney"}
[{"firstName":"Gokhan","lastName":"Coskun","login":"gcoskun","id":101}]
I wanted the user with the id 101 get returned and got instead all of the users returned.
Why are you doing id.id but passing a string? You either pass an object with an id prop (root.user({ id: '101' })) or replace id.id with simply id.
Also, it looks like the id fields in your user objects are of type number, while you are passing a string, so depending on the logic inside storage.select you might have to change that.
Passing a number id:
// Just mocking it for the example:
const storage = {
select(key, id) {
return [
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
{ firstName: 'George', lastName: 'Clooney', login: 'gclooney' },
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
// Depending on the logic here, these types need to match.
// Using == instead of === so that it's not required here.
].filter(user => user.id == id)
},
};
const root = {
user: (id) => {
console.log(`ID = ${ id }`);
// We make sure we only return a single user or null if there isn't one:
return storage.select('users', id)[0] || null;
},
};
const user = root.user('101');
console.log(user);
Passing an object with an id prop of type number:
// Just mocking it for the example:
const storage = {
select(key, id) {
return [
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
{ firstName: 'George', lastName: 'Clooney', login: 'gclooney' },
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
// Depending on the logic here, these types need to match.
// Using == instead of === so that it's not required here.
].filter(user => user.id == id);
},
};
const root = {
user: (query) => {
console.log(`ID = ${ query.id }`);
// We make sure we only return a single user or null if there isn't one:
return storage.select('users', query.id)[0] || null;
},
};
const user = root.user({ id: '101' });
console.log(user);

Find valid object from array of objects

I have the following array in my javascript code:
const users = [
{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
]
From this collection I want to retrieve user by email. So for example I will write:
my_function("test#user.com") it will return this one user. How can I do this?
You can use Array#find function. Pass a predicate into the function, which will return the first matched item based on that predicate.
const users = [
{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
]
function findByEmail(email) {
return users.find(x => x.email === email);
}
console.log(findByEmail('test#user.com'));
That's what the .find() method is for.
const users = [
{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
];
console.log(users.find(u => u.email == 'test#user.com'));
So .find() is called on the array, and receives a callback function. The callback will be invoked for each item in the array, for which you return the result of comparing the .email property to the email you're looking for.
As soon as your callback returns a true (or truthy) result, the iteration halts, and returns that object from .find(). If no is found, .find() returns undefined.
Note that this uses arrow function syntax. If you prefer, you can use traditional functions.
console.log(users.find(function(u) { return u.email == 'test#user.com' }));
There's always the good old fashioned for-loop:
const users = [{
id: 1,
email: 'test#user.com',
password: 'password',
access_token: 'test_user_access_token'
},
{
id: 2,
email: 'second#user.com',
password: 'password',
access_token: 'second_user_access_token'
}
]
function findUserByEmail(userList, desiredEmailAddress) {
for (let i = 0; i < userList.length; i++) {
var user = userList[i];
if (user.email === desiredEmailAddress) {
return user;
}
}
return null;
}
var desiredUser = findUserByEmail(users, 'second#user.com');
if (desiredUser) {
console.log('User found by email:\n');
console.log(desiredUser);
} else {
console.log('No user found with searched email address');
}

Meteor useraccounts:core role empty

I'm trying to learn Meteor through a video tutorial to finish the code did not get the same result. Here is the code:
Meteor.startup(function(){
if(Meteor.users.find().count() < 1){
var users= [
{
name: "Superuser",
email: "admin#example.com",
roles: ['admin']
}
];
_.each(users, function(user){
var id;
id = Accounts.createUser({
email: user.email,
password: "password",
profile:{
name: user.name
}
});
if(user.roles.length > 0){
Roles.addUsersToRoles(id, user.roles);
}
});
}
});
It is assumed that Meteor.roles.find.().fetch () console should appear: Object name: 'admin' _id. 'whatever'; but my pops me empty [ ].
I'm using alanning: roles from atmospherejs
Thanks in advance.
Have you installed the accounts-ui and accounts-passwords packages? It might be related to that. I suggest you to install the meteortoys:allthings to check what is wrong with your DB.
Meteor.startup(function() {
if (Meteor.users.find().count() < 1) {
var users = {
name: "Superuser",
email: "admin#example.com",
roles: ['admin']
};
var id;
id = Accounts.createUser({
email: user.email,
password: "password",
profile: {
name: user.name
}
});
if (user.roles.length > 0) {
Roles.addUsersToRoles(id, user.roles, 'defaultgroup');
}
});
}

Categories

Resources