Skip to content

Instantly share code, notes, and snippets.

@jeanlescure
Last active February 5, 2019 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeanlescure/0888a2a78a99c9b0cc5f0f68c37aa0a7 to your computer and use it in GitHub Desktop.
Save jeanlescure/0888a2a78a99c9b0cc5f0f68c37aa0a7 to your computer and use it in GitHub Desktop.
Javascript optimized function to rename keys of objects in an array
function renameObjectKeys(objArr, renameMap) {
  const keys = Object.keys(renameMap);

  for (let i = objArr.length - 1; i >= 0; i -= 1) {
    for (let j = keys.length - 1; j >= 0; j -= 1) {
      delete Object.assign(
        objArr[i],
        {[renameMap[keys[j]]]: objArr[i][keys[j]] }
      )[keys[j]];
    }
  }
}

This functions mutates all objects in a given object array, replacing all specified keys in the renameMap with their respective replacement values.

Example usage:

const users = [
  {
    name: "...",
    surname: "...",
    age: 30
  },
  // ...
];

const renameMap = {
  name: "firstName",
  surname: "lastName"
};

renameObjectKeys(users, renameMap);

console.log(users);
// output:
// [
//   {
//     firstName: "...",
//     lastName: "...",
//     age: 30
//   },
//   // ...
//  ];

Tested in production application with Node.js, arrays containing 300k+ objects with 50+ keys would take few milliseconds to remap the keys.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment