0

I want to get a user from a json file based on the id, what I have below only works if the ids are in order

 router.get('/:id', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
    people = JSON.parse( data );

    var user =  people.users[req.params.id]
    if (err) {
        res.status = 500;
        res.send(err).end();
        return;
    }
    console.log( user );
    res.end( JSON.stringify(user));
});
})

the json:

{"users[{"firstname":"stoffel","lastname":"clement","id":9},{"firstname":"stoffel","lastname":"clement","id":1},{"firstname":"liam","lastname":"murphy","id":"2"},{"firstname":"stoffel","lastname":"murphy","id":"3"}]}
  • You'll have to filter the array to search for the entry with the correct id. – Kevin B Jun 23 '16 at 19:04
  • 1
    Possible duplicate of [Find object by id in an array of JavaScript objects](http://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Kevin B Jun 23 '16 at 19:05

2 Answers2

0

Your code is accessing the users array by index. You want to search for it by id. (And when your users array is sorted according to id,the position in the array will match the id (assuming you are using zero-indexing) which is why it works).

If you're using a library like lodash you can do something like...

var user = _.find(users, ['id', req.params.id])

pyepye
  • 156
  • 1
  • 6
-1

Your JSON looks funky to me. I think you need a closing quote and colon after the users part, i.e.

{"users": [{"firstname":"stoffel","lastname":"clement","id":9},{"firstname":"stoffel","lastname":"clement","id":1},{"firstname":"liam","lastname":"murphy","id":"2"},{"firstname":"stoffel","lastname":"murphy","id":"3"}]};
sovemp
  • 1,402
  • 1
  • 13
  • 31
  • If this were the problem, it wouldn't work at all. *"what I have below only works if the ids are in order"* – Kevin B Jun 23 '16 at 19:02
  • additionally, if it were in fact the problem, answering the question isn't the right way to solve it... leave a comment asking for clarification and vote/flag to close as typo. – Kevin B Jun 23 '16 at 19:03