0

I am learning NodeJS . I am using a JSON Object to check if a user is present.

This is my JSON (users.json):

{
    "users": [{
        "fname": "Robert",
        "lname": "Downey Jr.",
        "password": "ironman"
    }, {
        "fname": "Chris",
        "lname": "Evans",
        "password": "cap"
    }, {
        "fname": "Chris",
        "lname": "Hemsworth",
        "password": "thor"
    }, {
        "fname": "Jeremy",
        "lname": "Renner",
        "password": "hawk"
    }]
}

Now I want to pass the fname value of one entry and see if it exists in the JSON Object.

This is what I'm doing :

var file = JSON.parse(fs.readFileSync('users.json', 'utf8'));
for (eachUser in file.users) {
            console.log(eachUser.fname);
        }

But I do not get the fname values but just undefined . I don't know what I am doing wrong.

Also is there a way to find if the value exists without having to iterate over the JSON Object ?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
v1shnu
  • 2,211
  • 8
  • 39
  • 68

3 Answers3

0
if ( typeof file !== 'undefined' && file )
{
   //do stuff if file is defined and not null
}
NiVeR
  • 9,644
  • 4
  • 30
  • 35
0

The problem is that eachUser gets set to each index in the array - not the object at that index. If you log just eachUser, you'll see

0
1
2
3

Instead, pull out the object first, and then gets its fname

for (index in file.users) {
  console.log(file.users[index].fname)
}

Here's a demo.

If you want to do this lookup without iterating through the array, you can re-shape your data into an object with fname as the key, so it would look like:

{
  "Robert": {
    "fname": "Robert",
    "lname": "Downey Jr.",
    "password": "ironman"
  },
  "Chris": {
    "fname": "Chris",
    "lname": "Evans",
    "password": "cap"
  },
  "Jeremy": {
    "fname": "Jeremy",
    "lname": "Renner",
    "password": "hawk"
  }
}

Of course, then either you won't be able to store any duplicate first names, or your need to make the values arrays.

Kristján
  • 18,165
  • 5
  • 50
  • 62
  • Yup ! this works. But can this be done without the loop. Just asking to see if there are any other ways of doing this. – v1shnu Jul 07 '15 at 16:19
-1

You have an issue in your iteration statement:

for (eachUser in file.users)

Feel free to use one the foreach statements described in this post such as:

file.users.forEach(function(user) {
    console.log(user.fname);
});

Cheers

Community
  • 1
  • 1
POZ
  • 583
  • 4
  • 11