Skip to content Skip to sidebar Skip to footer

Modify Object's Keys Without Creating New Object

I have following input: { foo: 4, bar: 3 } I want to modify the keys of this object to get: { x_foo_y: 4, x_bar_y: 3 } Is it possible to modify the object without creatin

Solution 1:

Yes, you just add the new keys and remove the 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 will impact the performance of the object. If you don't need to actually remove the properties, you could just set their values to undefined:

obj.x_foo_y = obj.foo;obj.foo = undefined;obj.x_bar_y = obj.bar;obj.bar = undefined;

Which won't have the impact (it's the delete that makes V8 put the object into "dictionary mode," which is much slower than V8's normal compiled class mode).

If you wanted to do this for all "own" properties in 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's okay for your use case
    }
}

Solution 2:

You need to add the keys and then delete the 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))

Post a Comment for "Modify Object's Keys Without Creating New Object"