繁体   English   中英

如何根据属性值过滤数组并返回对象数组

[英]How to filter an array based on property value and return array of objects

我有这个带有nameisPinned键的对象数组。 我只想根据isPinned将国家/地区名称存储在一个新数组中。 例如,如果澳大利亚和中国将isPinned设为 true,那么新数组将是:

const countriesFiltered = ["Australia", "China"]

const countries = [
    { name: "Australia", isPinned: true },
    { name: "China", isPinned: true },
    { name: "India", isPinned: false },
  ];

你会.filterisPinned然后按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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM