【问题标题】:How to filter an array based on property value and return array of objects如何根据属性值过滤数组并返回对象数组
【发布时间】:2022-01-06 18:51:56
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript arrays object


    【解决方案1】:

    你可以通过isPinned.filter,然后通过name.map

    const namesOfPinnedCountries = countries
        .filter(it => it.isPinned)
        .map(it => it.name)
    

    【讨论】:

      【解决方案2】:

      .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);

      【讨论】:

        【解决方案3】:

        你可以使用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);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-04-15
          • 2017-03-19
          • 2018-07-06
          • 1970-01-01
          相关资源
          最近更新 更多