修改对象的键而不创建新对象 [英] Modify object's keys without creating new object

查看:112
本文介绍了修改对象的键而不创建新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下输入内容:

{
  foo: 4,
  bar: 3
}

我想要修改此对象的键以获取:

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

{
  x_foo_y: 4,
  x_bar_y: 3
}

是否可以在不创建新对象的情况下修改对象? (可使用jQuery)

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

推荐答案

是的,您只需添加新密钥并删除旧密钥:

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;

请注意,在某些引擎(尤其是Chrome中的V8)上,这会影响引擎的性能物体.如果您不需要实际删除这些属性,则只需将其值设置为undefined:

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;

不会产生影响(是delete使V8将对象置于字典模式",这比V8的普通编译类模式要慢得多).

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

这篇关于修改对象的键而不创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆