首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用高阶函数,如果一个对象值为真,则返回另一个对象值(JavaScript)

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

Stack Overflow用户
提问于 2018-08-21 20:42:25
回答 5查看 63关注 0票数 0

我有一个对象:

代码语言: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"]。目前,我的代码返回一个包含整个对象的数组,其中包含物种狗。如下所示:

代码语言:javascript
运行
复制
const dogArray = animals.filter(function(animal) {
  return animal.species === 'dog';
 })

return dogArray;

// returns
// [{name: "Wally", species: "dog"}, 
// { name: "Roo", species: "dog"}]
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2018-08-21 20:44:23

只需将过滤数组的元素映射到它们的name属性:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
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)

票数 2
EN

Stack Overflow用户

发布于 2018-08-21 20:45:39

您可以使用destructuring映射该属性。

代码语言:javascript
运行
复制
const
    animals = [{ name: 'Fluffy', species: 'cat' }, { name: 'Crinkle', species: 'rabbit' }, { name: 'Wally', species: 'dog' }, { name: 'Roo', species: 'dog' }, { name: 'Felix', species: 'cat' }]
    dogArray = animals
        .filter(({ species }) => species === 'dog')
        .map(({ name }) => name);

console.log(dogArray);

票数 1
EN

Stack Overflow用户

发布于 2018-08-21 20:45:08

创建一个空数组,使用for循环遍历现有的dogArray,将名称推入新的数组,然后返回新的数组。

代码语言:javascript
运行
复制
const dogArray = animals.filter(function(animal) {
  return animal.species === 'dog';
 })

let dogNames = [];

for (let i in dogArray) {
  dogNames.push(dogArray[i].name);
}

return dogNames;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51948940

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档