Javascript 如何从数组中提取对象?
我有这样的代码,其中需要来自假数据库的用户名:Javascript 如何从数组中提取对象?,javascript,arrays,node.js,extract,Javascript,Arrays,Node.js,Extract,我有这样的代码,其中需要来自假数据库的用户名: const MY_FAKE_DB = require('./my_db.js') const username = 'jdoe2'; const user = MY_FAKE_DB.users[username]; console.log(user.name, user.passwordHash) “数据库”(my_db.js)是下一个: const users = { jdoe2: [{ usernam
const MY_FAKE_DB = require('./my_db.js')
const username = 'jdoe2';
const user = MY_FAKE_DB.users[username];
console.log(user.name, user.passwordHash)
“数据库”(my_db.js)是下一个:
const users =
{
jdoe2: [{
username: "jdoe2",
name: "Jhoe",
passwordHash: "1234"
}],
lmart: [{
username: "lmart",
name: "Luis",
passwordHash: "2345"
}]
}
我不知道如何从用户那里获得用户名为jdoe2的用户
感谢您的帮助您有一些问题是在这里造成的 首先要使用
require
,您应该从假数据库导出对象。比如:
// my_db.js
const users = {
jdoe2: {
username: "jdoe2",
name: "Jhoe",
passwordHash: "1234"
},
lmart: {
username: "lmart",
name: "Luis",
passwordHash: "2345"
}
}
module.exports = users // export users
注意,我更改了数据库。您将每个用户定义为一个数组,但这没有意义,您没有将其作为数组访问。在这里,每个用户都是一个对象
现在要使用它,您可以要求它,它应该可以按预期工作:
const users = require('./my_db.js') // the exported users becomes the `users`
const username = 'jdoe2';
const user = users[username];
console.log(user.name, user.passwordHash)
“我不知道如何通过编写代码从用户那里获得用户名为jdoe2的用户”,就是这样