Let’s say we have the following records of studentId and studentName and want to check a specific student name −
const studentDetails=
[
{
studentId:101,
studentName:"John"
},
{
studentId:102,
studentName:"David"
},
{
studentId:103,
studentName:"Carol"
}
]Create a custom function to find by name. Following is the code −
Example
const studentDetails=
[
{
studentId:101,
studentName:"John"
},
{
studentId:102,
studentName:"David"
},
{
studentId:103,
studentName:"Carol"
}
]
function findByName(name){
var flag=true;
for(var i=0;i<studentDetails.length;i++){
if(studentDetails[i].studentName==name){
flag=true;
break
} else{
flag=false;
}
}
if(flag==true){
console.log("The name found="+name);
} else{
console.log("The name not found="+name);
}
}
findByName("David");To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo106.js.
Output
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo106.js The name found=David