如何从数组中提取对象?

How to extract an object from an array?

我有这段代码,其中需要来自假数据库的用户名:

const MY_FAKE_DB = require('./my_db.js')  

const username = 'jdoe2'; 
const user = MY_FAKE_DB.users[username]; 
console.log(user.name, user.passwordHash)

而 "dataBase" (my_db.js) 是下一个:

    const users =
{
    jdoe2: [{
        username: "jdoe2",
        name: "Jhoe",
        passwordHash: "1234"
    }],

    lmart: [{
        username: "lmart",
        name: "Luis",
        passwordHash: "2345"
    }]
}

我不知道如何从用户那里得到用户名为 jdoe2 的用户。

感谢帮助

您有一些事情导致了这里的问题。

首先要使用 require,您应该 export 来自假数据库的对象。类似于:

// my_db.js
const users = {
    jdoe2: {
        username: "jdoe2",
        name: "Jhoe",
        passwordHash: "1234"
    },

    lmart: {
        username: "lmart",
        name: "Luis",
        passwordHash: "2345"
    }
}

module.exports = users // export users

注意我更改了数据库。您将每个用户定义为一个数组,但这没有意义并且您没有将它们作为数组访问。这里每个用户都是一个对象。

现在您可以 require 使用它,它应该会按预期工作:

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)