[英]How to filter an array based on property value and return array of objects
I have this array of objects with the name
and isPinned
keys.我有这个带有name
和isPinned
键的对象数组。 I would like to store only the country name in a new array based on what isPinned
is.我只想根据isPinned
将国家/地区名称存储在一个新数组中。 For example, if Australia and China have isPinned
as true, then the new array would be:例如,如果澳大利亚和中国将isPinned
设为 true,那么新数组将是:
const countriesFiltered = ["Australia", "China"]
const countries = [
{ name: "Australia", isPinned: true },
{ name: "China", isPinned: true },
{ name: "India", isPinned: false },
];
You would .filter
by isPinned
and then .map
by name
你会.filter
按isPinned
然后按name
.map
const namesOfPinnedCountries = countries
.filter(it => it.isPinned)
.map(it => it.name)
.filter()
and .map()
is the classical solution, but you can also do it with .reduce()
: .filter()
和.map()
是经典的解决方案,但您也可以使用.reduce()
来实现:
const countries = [ { name: "Australia", isPinned: true }, { name: "China", isPinned: true }, { name: "India", isPinned: false }, ]; const res=countries.reduce((a,c)=> c.isPinned?[...a,c.name]:a,[]); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.