javascript - 使用高阶函数,如果另一个值为 true,则返回一个对象值 (JavaScript)

标签 javascript arrays object higher-order-functions

我有一个对象:

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));

或者将两者合并为一个reduce:

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)

关于javascript - 使用高阶函数,如果另一个值为 true,则返回一个对象值 (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51948940/

相关文章:

javascript - 在 Django 上导入 JS 文件

javascript - 将对象转换为具有 lodash 中父子关系的数组

java - 如何使用输入来创建对象

Java:ToString() 每次打印相同的哈希码

PHP将相同的xml对象键存储到不同的mysql表

javascript - 自定义 html 数据列表下拉列表

javascript - 使用 jQuery 计算两个特定行之间的表行数

javascript - ESLint 一致返回和嵌套回调

c - 尝试在 MIPS 中创建并打印数组中的元素

arrays - 类型末尾的双问号是什么意思?