[英]How to filter an array based on property value and return array of objects
我有这个带有name
和isPinned
键的对象数组。 我只想根据isPinned
将国家/地区名称存储在一个新数组中。 例如,如果澳大利亚和中国将isPinned
设为 true,那么新数组将是:
const countriesFiltered = ["Australia", "China"]
const countries = [
{ name: "Australia", isPinned: true },
{ name: "China", isPinned: true },
{ name: "India", isPinned: false },
];
你会.filter
按isPinned
然后按name
.map
const namesOfPinnedCountries = countries
.filter(it => it.isPinned)
.map(it => it.name)
.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);
您可以使用flatMap :
const countries = [ { name: "Australia", isPinned: true }, { name: "China", isPinned: true }, { name: "India", isPinned: false }, ]; const countriesFiltered = countries.flatMap(i => i.isPinned? i.name: []); console.log(countriesFiltered);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.