我有一个对象:
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/