数组,hash map互转 + ts泛型的应用

723 阅读1分钟

数组,hash map互转 + ts泛型的应用

  • hash map就是将数组中元素的一个属性的值作为key,然后元素本身作为value。
  • 这样通过新生成hash map对象和key可以快速 读取/查找 原本数组的元素了。
  • 目的是为了减少遍历数组。
interface ItestData {
  _id?: string,
  name: string
}

const testData1: ItestData[] = [
  { _id: '1', name: 'name1' },
  { _id: '2', name: 'name2' }
]

const testData2: { [key: string]: ItestData } = {
  1: { _id: '1', name: 'name1' },
  2: { _id: '2', name: 'name2' }
}

export const arrToObj = <T extends { _id?: string }>(arr: Array<T>): { [key: string]: T } => {
  return arr.reduce((result, current) => {
    if (current._id) {
      result[current._id] = current
    }
    return result
  }, {} as { [key: string]: T })
}

export const objToArr = <T>(obj: { [key: string]: T }): Array<T> => {
  return Object.keys(obj).map(key => obj[key])
}

const result1 = arrToObj(testData1)
console.log(result1)

const result2 = objToArr(testData2)
console.log(result2)