Artem_Astakhov Artem_Astakhov - 5 months ago 16
Javascript Question

Node.js undefined properties

I'm trying to create a log in window. My code is simple.



var employees = {
'1' : {
firstName: '',
lastName: '',
login: 'qwerty',
password: '12345',
},
'2' : {
login: 'asdfg',
password: '12345',
},
};

app.post('/main', function(req, res) {
if (!req.body) return res.sendStatus(400);
console.log(req.body);
for (var key in employees) {
console.log(key['login']);
console.log(key['password']);
if ((key.login == req.body.login) && (key.password == req.body.password)) {
res.render('main');
} else {
app.get('/', function(req,res) {
res.send(createIndexPage());
});
};
};
});





Why key.login and key.password return undefined?
And why else block does not run when if statement is wrong?

Answer

Look at what the value of key actually is:

var employees = {
  '1': {
    firstName: '',
    lastName: '',
    login: 'qwerty',
    password: '12345',
  },
  '2': {
    login: 'asdfg',
    password: '12345',
  },
};

for (var key in employees) {
  console.log(key);
}

It is the property name (as a string), not the value of the property.

console.log(employees[key]['login']); will give you what you are looking for.

Comments