Ajv2324 Ajv2324 - 5 months ago 7
Node.js Question

How to search through JSON objects to find a specific parameter value?

I have some JSON that looks, basically, like this:

{
"inactive_user": {
"name": "A",
"id": "1",
"dob": "01011990",
},
"active_staff": {
"id": "B",
"dob": "2",
},
"active_student": {
"name": "C",
"pid": "3",
"dob": "01011990",
},
"no_securityquestion": {
"name": "D",
"pid": "4",
"dob": "01011990",
}
}


What I want to do is, based on an id that is given from the request, return the user (inactive_user, active_staff, etc) that has that id.

How can I do this? What I've tried so far is:

for (var parent in userObject){
if(userObject.parent.pid === pid){
console.log(userObject.parent);
reply(userObject.parent);
}
}


But userObject.parent (where userObject is the entire JSON file) just returns undefined, which is weird because parent will return each of the names of the parent objects in the file (inactive_user and what not)

Answer

To reference a dynamic key in an object, you must use the bracket notation.

for (var parent in userObject){
    if(userObject[parent].pid === pid){
        console.log(userObject[parent]);
        reply(userObject[parent]);
    }
}

Also, I see in your data that you have some entries where the id is not pid but simply id; I don't know if you want them to be treated the same way as pid, but if it's the case, you should update your condition accordingly.

Comments