javascript - Check if value exists in JSON Object -


this question has answer here:

i learning nodejs . using json object check if user present.

this 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 want pass fname value of 1 entry , see if exists in json object.

this i'm doing :

var file = json.parse(fs.readfilesync('users.json', 'utf8')); (eachuser in file.users) {             console.log(eachuser.fname);         } 

but not fname values undefined . don't know doing wrong.

also there way find if value exists without having iterate on json object ?

the problem eachuser gets set each index in array - not object @ index. if log eachuser, you'll see

0 1 2 3 

instead, pull out object first, , gets fname

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

here's demo.

if want lookup without iterating through array, can re-shape data object fname key, 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, either won't able store duplicate first names, or need make values arrays.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -