Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify object's keys without creating new object [duplicate]

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 creating new one ? (jQuery available)

like image 604
hsz Avatar asked Apr 17 '26 22:04

hsz


1 Answers

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
    }
}
like image 89
T.J. Crowder Avatar answered Apr 20 '26 14:04

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!