renameKey

Renames a key in an object.

1. Code

const renameKey = <T extends object, K extends keyof T, N extends string>(
  obj: T,
  key: K,
  newKey: N
): Omit<T, K> & {
  [P in N]: T[K];
} => {
  const newObj: any = { ...obj };
  newObj[newKey] = newObj[key];
  delete newObj[key];
  return newObj as Omit<T, K> & { [P in N]: T[K] };
};

export default renameKey;

2. Installation

npx @jrtilak/lazykit@latest add renameKey

3. Description

The renameKey function renames a key in an object and returns a new object with the renamed key.

4. Props

Prop

Type

Default Value

object*object---
key*string---
newKey*string---

5. Examples

import rename from ".";

const obj = { a: 1, b: 2, c: 3 };
const result = rename(obj, "a", "d");
console.log(result);
// Expected output: { b: 2, c: 3, d: 1 }