I'm currently working on a program that takes user input (library, authorName) and displays the titles of books written by the author.
Here is an example library structure:
let library = [
{ author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
{ author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
{ author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];
This is my code snippet:
let library = [
{ author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
{ author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
{ author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];
function searchBooks(library, author) {
for (author in library) { //enumerate
if (author in library) {
let line = Object.values(library[0]) // find line of the wanted author
let result = (line[0] + "," + line[1]) // store author name and title name
return result
} else {
return "NOT FOUND"
}
}
}
console.log(searchBooks(library, 'Bill Gates'))
The output generated looks like this:
Bill Gates,The Road Ahead
The challenge:
Regardless of which author I input into the searchBook
, it always returns Bill Gates as the first entry in the library. It seems to not be iterating through all entries. Why might this be happening?
Initially, I thought about avoiding hard coding [0] and [1] and instead using i and i++. However, this approach resulted in a
TypeError: Cannot convert undefined or null to object
error message.