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']);
});
});
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));
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.