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

时间:2018-08-21 12:42:25

标签: 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"]。目前,我的代码返回一个数组,其中包含带有对象dog的整个对象。见下文:

const dogArray = animals.filter(function(animal) {
  return animal.species === 'dog';
 })

return dogArray;

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

5 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您可以使用destructuring映射属性。

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

答案 2 :(得分:0)

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

const dogArray = animals.filter(function(animal) {
  return animal.species === 'dog';
 })

let dogNames = [];

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

return dogNames;

答案 3 :(得分:0)

/application-a/

答案 4 :(得分:0)

您可以使用.filter(),然后使用.map()

const animals = [
  {name: 'Fluffy', species: 'cat'},
  {name: 'Crinkle', species: 'rabbit'},
  {name: 'Wally', species: 'dog'},
  {name: 'Roo', species: 'dog'},
  {name: 'Felix', species: 'cat'},
];

const dogNames = animals
  .filter(animal => animal.species === 'dog')
  .map(dog => dog.name);

console.log(dogNames);