0

I have this array of object

const database = {
    users: [
    {
        id:1,
        name: "John",
        email: "[email protected]",
        passowrd: "h4ckM3!ifuc4n",
        entries: 0,
        joined: new Date(),

    },
    {
        id:2,
        name: "Mila",
        email: "[email protected]",
        passowrd: "mila",
        entries: 0,
        joined: new Date(),

    },
    {
        id:3,
        name: "Luke",
        email: "[email protected]",
        passowrd: "123",
        entries: 0,
        joined: new Date(),

    }

    ]
}

I'm trying to query a specific element from that array

app.get("/profile/:id", function (req, res) {

    console.log(req.params.id);
    // const user = _.find(database.users, {id: req.params.id });

    var user = _.find(database.users, {id:req.params.id});
    console.log(user);

    if(!user) {
       res.status(404).json("no user found");
    }

});

I kept getting

Example app listening on port 3002!
1
undefined

Any hints for me?

2
  • 2
    req.params.id will be string...convert to number Commented Oct 13, 2020 at 0:13
  • Why bother with Lodash? const user = database.users.find(({ id }) => id == req.params.id). The == comparison will compare numbers with numeric strings without requiring parsing Commented Oct 13, 2020 at 1:35

1 Answer 1

4

You really do not need lodash for that. I would not suggest using it since it creates unnecessary overhead.

const user = database.users.find(user => user.id == req.params.id)

Should work just fine.

be aware that == is an unsafe check, and in case req.params.id is undefined it would match a user with the id of 0.

to mitigate this you could convert the req.params.id to a number and use a safe check operator === instead. (it checks that they aren't just comparable, but actually the same type and value)

const user = database.users.find(user => user.id === parseInt(req.params.id, 10)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Jonas, it's a clean and simple JS solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.