es-toolkit
Version:
A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.
31 lines (30 loc) • 957 B
JavaScript
//#region src/object/mapKeys.ts
/**
* Creates a new object with the same values as the given object, but with keys generated
* by running each own enumerable property of the object through the iteratee function.
*
* @template T - The type of the object.
* @template K - The type of the new keys generated by the iteratee function.
*
* @param object - The object to iterate over.
* @param getNewKey - The function invoked per own enumerable property.
* @returns Returns the new mapped object.
*
* @example
* // Example usage:
* const obj = { a: 1, b: 2 };
* const result = mapKeys(obj, (value, key) => key + value);
* console.log(result); // { a1: 1, b2: 2 }
*/
function mapKeys(object, getNewKey) {
const result = {};
const keys = Object.keys(object);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = object[key];
result[getNewKey(value, key, object)] = value;
}
return result;
}
//#endregion
exports.mapKeys = mapKeys;