Reputation: 1
Using JavaScript, is it possible to change an existing key name in an object, other than by removing the entire key-value pair and adding a new one in its place?
The sort of thing about which I am asking would, if possible, look generally like this:
myObj = {'a':1, 'b':2,};
Object.keys(myObj)[i] = 'newKeyName';
...except that instead of editing an array made by extracting the key names, one would actually edit the key name itself in the source object.
Upvotes: 0
Views: 66
Reputation: 491
Another solution with some perf.
obj = {'a':1,'b':2}
oldKey = 'a'
newKey = 'x'
if (oldKey !== newKey) {
Object.defineProperty(obj, newKey,
Object.getOwnPropertyDescriptor(obj, oldKey));
delete obj[oldKey];
}
Upvotes: 0
Reputation: 727
Nope, that's the best way to do it.
var a = { b: 'c', d: 'e' };
a.f = a.b;
delete a.b;
console.log(a); // { d: 'e', f: 'c' }
Upvotes: 3