I am trying to write a program that takes an input (library, authorName) and returns the title of books the author wrote.
The library looks like this:
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 }
];
My code looks like this:
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 looks like this:
Bill Gates,The Road Ahead
The problem:
No matter what author I will input into searchBook it returns Bill Gates, the first line of the library. Thus, it does not enumerate I guess. But why not?
I first thought maybe I have to avoid hard coding [0] and [1] and instead use i and i++. But this does not seem to work either as it then outputs TypeError: Cannot convert undefined or null to object
for (author in library)iterates over the keys of the array.let line = Object.values(library[0])also, this would always gets the first item in the array, regardless of how many loops you have.