@pengzhanbo/utils - v3.4.1
    Preparing search index...

    Function keyBy

    • Creates an object composed of keys generated from the results of running each element of an array through the given function.

      The opposite of groupBy, this function creates an object where each key is the result of the iteratee function, and the value is the last element that produced that key.

      创建一个对象,键由数组的每个元素经过给定函数运行后的结果生成。

      groupBy 相反,此函数创建一个对象,其中每个键是 iteratee 函数的结果, 值是产生该键的最后一个元素。

      Type Parameters

      • T
      • K extends PropertyKey

      Parameters

      • array: readonly T[]

        The array to convert. 要转换的数组

      • iteratee: (item: T) => K

        The function to transform elements into keys. 将元素转换为键的函数

      Returns Record<K, T>

      An object with keys mapped to the last element that produced each key. 键映射到产生该键的最后一个元素的对象

      Uses Map for O(1) key lookup, overall O(n) time complexity

      使用 Map 实现 O(1) 键查找,整体时间复杂度 O(n)

      keyBy([{ id: 1, name: 'a' }, { id: 2, name: 'b' }], x => x.id)
      // => { 1: { id: 1, name: 'a' }, 2: { id: 2, name: 'b' } }
      keyBy(['one', 'two', 'three'], x => x.length)
      // => { 3: 'two', 5: 'three' }