【问题标题】:Array of objects map with dynamic column names具有动态列名的对象映射数组
【发布时间】:2021-01-04 15:16:21
【问题描述】:

说,我有一个包含国家、州、城市的对象数组。我想在这个数组上使用 .map 来根据我的要求获得唯一的国家或州或城市。我该如何编写一个方法接受一个列名,我想映射并相应地返回结果。

GetUniqueValues(colName) { // colName could be county or state
const uniqueVals = Array.from(new Set(this.myArray.map(item => item.country))); // how do I include colName here without writing item.country or item.state as I have many other fields to map
return uniqueVals;
}

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:
    type Address = {
      country: string
      state: string
      city: string
    }
    
    function findUnique<T, K extends keyof T>(arr: T[], key: K) {
      return new Set(arr.map((address) => address[key]))
    }
    
    const arr: Address[] = [
      { country: 'A', state: 'C', city: 'C' },
      { country: 'A', state: 'B', city: 'C' },
      { country: 'B', state: 'B', city: 'A' },
      { country: 'D', state: 'A', city: 'B' }
    ]
    
    console.log(findUnique(arr, 'city')) // { 'C', 'A', 'B' }
    console.log(findUnique(arr, 'country')) // { 'A', 'B', 'D' }
    console.log(findUnique(arr, 'state')) // { 'C', 'B', 'A' }
    

    【讨论】:

      【解决方案2】:

      像这样尝试:

      const uniqueVals = Array.from(new Set(this.myArray.map(item => item[colName])));
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-04
        • 1970-01-01
        • 1970-01-01
        • 2019-07-26
        • 2011-07-24
        • 1970-01-01
        • 2020-11-03
        • 2018-12-02
        相关资源
        最近更新 更多