javascript - 使用高阶函数,如果另一个值为真,则返回一个对象值 (JavaScript)
问题描述
我有一个对象:
const animals = [
{name: 'Fluffy', species: 'cat'},
{name: 'Crinkle', species: 'rabbit'},
{name: 'Wally', species: 'dog'},
{name: 'Roo', species: 'dog'},
{name: 'Felix', species: 'cat'},
]
我想使用更高阶的函数,例如 filter() 方法来获取动物对象数组并返回一个仅包含所有狗名称的数组,即["Wally", "Roo"]
. 我的代码目前返回一个数组,其中包含整个对象以及其中的物种狗。见下文:
const dogArray = animals.filter(function(animal) {
return animal.species === 'dog';
})
return dogArray;
// returns
// [{name: "Wally", species: "dog"},
// { name: "Roo", species: "dog"}]
解决方案
只需将过滤后的数组的元素映射到它们的 name 属性:
const animals = [
{name: 'Fluffy', species: 'cat'},
{name: 'Crinkle', species: 'rabbit'},
{name: 'Wally', species: 'dog'},
{name: 'Roo', species: 'dog'},
{name: 'Felix', species: 'cat'},
]
const dogArray = animals.filter(animal => animal.species === 'dog');
console.log(dogArray.map(dog => dog.name));
或者将两者合二为一:
const animals = [
{name: 'Fluffy', species: 'cat'},
{name: 'Crinkle', species: 'rabbit'},
{name: 'Wally', species: 'dog'},
{name: 'Roo', species: 'dog'},
{name: 'Felix', species: 'cat'},
]
let dogArray = animals.reduce((dogs, animal) => {
if (animal.species === "dog") dogs.push(animal.name);
return dogs;
}, []);
console.log(dogArray)
推荐阅读
- python - 在报告在文本中找到位置的模型的准确性时,应该使用哪种相似性度量?
- c# - 泛型列表的函数重载
问题 - powerbi - 如何在power bi查询中比较两个日期
- php - com.android.volley.AuthFailureError 在发出 POST 请求以服务器为用户注册
- javascript - 为什么这个 response.end(callback) 被调用了两次?
- android - 使用 unity3d 创建的 Android apk 在某些手机上无法打开
- php - 试图使用 [] 来获取参数的值
- ios - 单击 UITextField 时如何显示联系人?
- java - 一个 flink 作业中的两个数据流
- r - 如何在 keras(R) 中构建张量流模型以进行多标签分类?