简体   繁体   English

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

[英]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.我有这个带有nameisPinned键的对象数组。 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你会.filterisPinned然后按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);

You can use flatMap :您可以使用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.

相关问题 根据属性值过滤嵌套的对象数组 - Filter nested array of objects based on a property value 如何根据属性值比较和过滤数组对象? - How to compare and filter objects of array based on property value? 根据来自不同对象数组的属性和值过滤对象数组 - Filter an array of objects based on a property and value from a different array of objects 过滤基于 object 的对象数组,其中数组作为其属性值在反应 - filter an array of objects based on an object with an array as it's property value in react 按属性值过滤对象数组 - Filter array of objects by property value 如何根据对象数组中属性的第一个字符过滤对象数组? - How to filter an array of objects based on the first character of a property in the array of object? Angular2-根据对象属性的值过滤对象数组 - Angular2 - Filter array of objects based on value of an object property 是否使用下划线基于属性值过滤对象数组? - Filter array of objects based on property value regardless of case using Underscore? 检查对象数组中的属性,并根据该值返回一个字符串 - check for a property in array of objects and return a string based on the value javascript根据条件从对象的嵌套数组返回属性值 - javascript return property value from nested array of objects based on condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM