Skip to content

数组优化为哈希表

概念

  • 许多时候,数据会是 Array 形式,如

    js
    [
        {
            id: '1',
            name: 'xiuaoming'
        },
        {
            id: '2',
            name: 'xiaomei'
        }
    ]

    但因为 React 的不可变数据规则,删改查操作较麻烦,并且需要循环数组,效率较低

  • 可转变为 HashMap 形式,优化效率

    js
    {
        '1': {
            id: '1',
            name: 'xiaoming'
        },
        '2': {
            id: '2',
            name: 'xiaomei'
        }
    }

转换函数

typescript
interface IObj<T> {
 [key: string]: T
}

const ArrToObj = <T extends { id: string }> (arr: T[]): IObj<T> => {
 return arr.reduce((pre: IObj<T>, cur: T): IObj<T> => {
     pre[cur.id] = cur
     return pre
 }, {})
}

const objToArr = <T> (obj: IObj<T>): T[] => {
 return Object.keys(obj).map(id => obj[id])
}

不可变数据规则下增删改查思想

  1. js
    const newList = { ...list, ['3']: { id: '3', name: 'xiaoxiao' } }
  2. js
    const { ['2']: deleteItem, ...afterDeleteList } = list
  3. js
    const newItem = { ...list['2'], name: 'xiaomei2' }
    const newList = { ...list, ['2']: newItem }
  4. js
    const item = list['2']