[英]Can I use filter to extract values from an array of objects?
我有一个对象数组:
const books = [
{
title: 'Book',
author: 'Name'
},
{
title: 'Book2',
author: 'Name2'
}
];
我想使用filter方法将标题提取到一个数组中。 到目前为止,我尝试过这个,但数组返回了 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 来完成。 但我正在尝试使用过滤器来完成它。
如果您想获取某些已过滤书籍的标题,则可以通过将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
(或任何为truthy)项目保持否则将被删除。
示例:只保留奇数:
[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
,这是一个“假”值。 此功能与说“忽略所有书籍”相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.