首页 > 解决方案 > 使用高阶函数,如果另一个值为真,则返回一个对象值 (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"}]

标签: javascriptarraysobjecthigher-order-functions

解决方案


只需将过滤后的数组的元素映射到它们的 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)


推荐阅读