I need to loop through an array of objects, and prompt the user to enter a student's name. if the name exists I need to print the student's data to the screen or else keep on iterating until the user types quit.
The issue I have is, if I type the name of student of the last object, the student's records will not print until the loop completes.
Please see the code below:
var students = [{
name: 'hacene',
track: 'Full Stack JavaScript',
achievements: 12,
points: 1226
},
{
name: 'dave',
track: 'PHP Development',
achievements: 128,
points: 14868
},
{
name: 'layla',
track: 'iOS Development',
achievements: 8,
points: 901
},
{
name: 'mika',
track: 'Front-End Development',
achievements: 15,
points: 1666
},
{
name: 'heisenberg',
track: 'Blue Meth Manufacturing',
achievements: 99,
points: 9999
}
];
var student;
var records = '';
var search;
// Print function to print the content
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
// Access each students records in the array / a loop is needed to achieve this
for (var i = 0; i < students.length; i++) {
student = students[i];
console.log(student);
search = prompt('Please enter a student\'s name to see his records: ');
search = search.toLocaleLowerCase();
console.log(search);
if (search === student.name) {
records += '<h2><strong>Student: ' + student.name + '</strong><h2>';
records += '<p>Track: ' + student.track + '</p>';
records += '<p>Points: ' + student.points + '</p>';
records += '<p>Achievements: ' + student.achievements + '</p>';
break;
} else if (search === 'quit') {
break;
}
}
// Print the students' name; track, achievments and points
print(records);
What I need is, to be able to print the records of a student, from the first prompt even if he's the last on the list.
record = students.find((student) => { return student.name === prompt.toLowerCase() })