Changing object keys without creating a new object
2 answers
Yes, you just add new keys and remove old ones:
obj.x_foo_y = obj.foo;
delete obj.foo;
obj.x_bar_y = obj.bar;
delete obj.bar;
Note that on some engines (notably V8 in Chrome) this affects the performance of the object. If you don't really need to delete properties, you can simply set their values to undefined
:
obj.x_foo_y = obj.foo;
obj.foo = undefined;
obj.x_bar_y = obj.bar;
obj.bar = undefined;
Which will have no effect (this delete
is what V8 does is putting the object in "dictionary mode" which is much slower than the standard compiled V8 class mode).
If you want to do this for all the "own" properties of an object:
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
obj["x" + key + "y"] = obj[key];
delete obj[key]; // Or obj[key] = undefined if that okay for your use case
}
}
+4
source to share
You need to add keys and then delete old ones.
var obj = {
foo: 4,
bar: 3
};
obj.x_foo_y = obj.foo;
obj.x_bar_y = obj.bar;
delete obj.foo;
delete obj.bar;
alert(JSON.stringify(obj))
+4
source to share