Changing object keys without creating a new object

I have the following input:

{
  foo: 4,
  bar: 3
}

      

I want to change the keys of this object to get:

{
  x_foo_y: 4,
  x_bar_y: 3
}

      

Is it possible to modify an object without creating a new one? (jQuery available)

+3


source to share


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


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))
      

Run codeHide result


+4


source







All Articles