【问题标题】:How to extract an object from an array?如何从数组中提取对象?
【发布时间】:2018-11-19 16:26:49
【问题描述】:

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

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 的用户。

感谢您的帮助

【问题讨论】:

  • "我不知道怎么从用户那里得到用户名为jdoe2的用户" 写代码就是这样

标签: javascript arrays node.js extract


【解决方案1】:

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

首先使用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)

【讨论】:

    猜你喜欢
    • 2020-06-08
    • 1970-01-01
    • 2018-06-30
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多