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

    Function objectMap

    • Map key/value pairs for an object, and construct a new one

      为一个对象映射键值对,并构造一个新对象

      Type Parameters

      • K extends string

        The type of the key (extends PropertyKey) / 键的类型(继承 PropertyKey)

      • V

        The type of the value / 值的类型

      • NK extends PropertyKey = K
      • NV = V

      Parameters

      • obj: Record<K, V>

        The source object. 源对象

      • mapper: (key: K, value: V) => [NK, NV] | undefined

        The mapper function to transform key/value pairs. 用于转换键值对的映射函数

      Returns Record<NK, NV>

      A new object with transformed key/value pairs. 具有转换后键值对的新对象

      Dangerous keys (__proto__, constructor, prototype) are silently filtered out from the result object. If the mapper function returns undefined for a key/value pair, that entry is removed from the result.

      危险键(__proto__constructorprototype)会被静默过滤,不会出现在结果对象中。 如果映射函数返回 undefined,则该键值对会从结果中被移除。

      // Transform:
      objectMap({ a: 1, b: 2 }, (k, v) => [k.toString().toUpperCase(), v.toString()])
      // { A: '1', B: '2' }
      // Swap key/value:
      objectMap({ a: 1, b: 2 }, (k, v) => [v, k])
      // { 1: 'a', 2: 'b' }
      // Filter keys:
      objectMap({ a: 1, b: 2 }, (k, v) => k === 'a' ? undefined : [k, v])
      // { b: 2 }