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.)
1 Answer 1
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 ahasOwnProperty
check to ensure that you're only checking the instance, not the prototype.
-
\$\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\$Guy– Guy2016年12月04日 03:44:00 +00:00Commented Dec 4, 2016 at 3:44
-
\$\begingroup\$ @Guy There is, and you just did it. Just be wary about the consequences. \$\endgroup\$Joseph– Joseph2016年12月05日 00:35:12 +00:00Commented Dec 5, 2016 at 0:35