So I am doing a npm test on object books. I want to get the value of the title property from the books object. If I call the function getTheTitles(books), the value of both 'Book' and 'Book2' will be returned. I tried writing my code and run npm test but the result shown that there is one undefined in addition to Book and Book2. Is there some changes need to be done on my getTheTiles function ?The following are the code :
const books = [
{
title: 'Book',
author: 'Name'
},
{
title: 'Book2',
author: 'Name2'
}
]
let titles = ['title'];
const getTheTitles = function(item) {
return titles.map(function(k) {
return item[k];
})
}
getTheTitles(books);
------------------ Below are the npm test and it's expected result -----------
const getTheTitles = require('./getTheTitles')
describe('getTheTitles', () => {
const books = [
{
title: 'Book',
author: 'Name'
},
{
title: 'Book2',
author: 'Name2'
}
]
test('gets titles', () => {
expect(getTheTitles(books)).toEqual(['Book','Book2']);
});
});
CodePudding user response:
The callback for map
function is not quite correct.
You can simply do
const data = [{ title: 'Book', author: 'Name' }, { title: 'Book2', author: 'Name2' }];
const getTheTitles = (books) => books.map((book) => book.title);
console.log(getTheTitles(data));
CodePudding user response:
Yes the function needs some tweaking. Something like this should work:
const getTheTitles = bookList => {
return bookList.map(book => book.title);
}
That will give you a list of the titles.