我有一个对象数组:
const books = [
{
title: 'Book',
author: 'Name'
},
{
title: 'Book2',
author: 'Name2'
}
];
我想使用过滤器方法将标题提取到数组中。到目前为止,我尝试了这个,但数组返回了 2 个原始对象:
const getTheTitles = function(array) {
const filteredArray = array.filter(function(book) {
return book.title;
})
return filteredArray;
}
我也试过这个,但它会导致一个空数组(不知道为什么):
const getTheTitles = function(array) {
const filteredArray = array.filter(function(book) {
book.title;
})
return filteredArray;
}
我知道这可以使用地图来完成。但我正在尝试使用过滤器来完成它。
如果你想获取某些过滤书籍的标题,那么要么通过将map
链接到filter
来实现,如下所示:
let filteredBookTitles = books
.filter(book => book.author === "Some Name") // first filter (us any criteria here to select only the books you want)
.map(book => book.title); // then get the titles of those filtered books
演示:
const books = [{ title: "Animal Farm", author: "George Orwell" }, { title: "Oliver Twist", author: "Charles Dickens" }, { title: "1984", author: "George Orwell" }];
let georgeOrwellBooks = books.filter(book => book.author === "George Orwell")
.map(book => book.title);
console.log(georgeOrwellBooks);
或者使用reduce
在仅循环数组一次的情况下执行这两项操作,如下所示:
let filteredBookTitles = books.reduce((acc, book) => { // for each book in the books array
if(book.author === "Some Name") { // if the book matches the criteria
acc.push(book.title); // add its title to the results array
}
return acc;
}, []);
演示:
const books = [{ title: "Animal Farm", author: "George Orwell" }, { title: "Oliver Twist", author: "Charles Dickens" }, { title: "1984", author: "George Orwell" }];
let georgeOrwellBooks = books.reduce((acc, book) => {
if(book.author === "George Orwell") {
acc.push(book.title);
}
return acc;
}, []);
console.log(georgeOrwellBooks);
只能使用Array#filter
删除项目,而不能转换项目。筛选功能应用于每个项目。如果函数返回true
(或任何真实的内容),则保留该项,否则将被删除。
示例:仅保留奇数:
[1,2,3,4,5].filter(n => n % 2 !== 0);
//=> [1,3,5]
示例:从布尔数组中删除false
:
[true,false,true,false].filter(b => b);
//=> [true,true]
您要做的是转换所有项目。 例如,从[{n:1},{n:2},{n:3}]
转换为[1,2,3]
。在这种情况下,您需要Array#map
将函数应用于所有项目并创建一个包含结果的新数组:
[{n:1},{n:2},{n:3}].map(o => o.n);
//=> [1,2,3]
为什么此函数返回所有书籍?
const getTheTitles = function(array) {
const filteredArray = array.filter(function(book) {
return book.title;
})
return filteredArray;
}
问题是您的过滤器函数计算book.title
以决定是否保留 book 对象。但是,您所有的书都有一个标题,因此此功能与说"这本书有标题吗?
为什么这个函数根本不返回书籍?
const getTheTitles = function(array) {
const filteredArray = array.filter(function(book) {
book.title;
})
return filteredArray;
}
问题是您的过滤器函数实际上并没有显式返回任何内容。当一个函数没有return
语句时,默认情况下它会返回undefined
,这是一个"假"值。此功能与说"忽略所有书籍">相同