Swap the names/properties in a JavaScript object Is there a more elegant way to do this in JavaScript?

function swapKey(obj, oldKey, newKey) {
  if (obj[oldKey]) {
    obj[newKey] = obj[oldKey];
    delete obj[oldKey];
  }
  return obj;
}


(I understand that it mutates the original object and is not functional and makes the returning of obj somewhat redundant and that's okay for this particular question.)
So the idea is to change the key of a given pair. Few issues:


Your code doesn't guard against existing keys. If my newKey is an already existing key, it would overwrite the existing value, and delete the old key.
Like mentioned, mutation. Unless you're fully aware of the things that reference the object or have mechanisms in place to capture suddenly missing properties, you shouldn't mutate in-place. In the case above, if you accidentally delete an existing key another piece of code expects to exist, this will cause unexpected breakage.
Your condition will return true for prototype members. Always do a hasOwnProperty check to ensure that you're only checking the instance, not the prototype.