1
\$\begingroup\$

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.)

asked Dec 2, 2016 at 13:30
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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.

answered Dec 2, 2016 at 14:03
\$\endgroup\$
2
  • \$\begingroup\$ Great points - thanks @Joseph the Dreamer. So there's no in-place way to rename the key of a key/value pair then? \$\endgroup\$ Commented Dec 4, 2016 at 3:44
  • \$\begingroup\$ @Guy There is, and you just did it. Just be wary about the consequences. \$\endgroup\$ Commented Dec 5, 2016 at 0:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.