简体   繁体   English

如何动态替换javascript对象属性名称

[英]How to replace the javascript object property name dynamically

I have created a JavaScript object like 我创建了一个JavaScript对象,例如

var obj={}
var prop = {}
prop.name= "name",
prop.value = "10"
obj[old_name] = prop;

I need to change the old_name to new_name . 我需要将old_name更改为new_name I have tried 我试过了

obj[new_name] = obj[old_name];
delete obj[old_name];

And it works but, the object order gets changed. 它有效,但是对象顺序已更改。

For example: 例如:

{"obj1":{"name:name","value:10"},"obj2":{"name:name","value:10"}}

If I replace obj1 with objone , like this: 如果我用objone替换obj1 ,像这样:

obj[objone ] = obj[obj1];
delete obj[obj1 ];

The object order changed to: 对象顺序更改为:

{"obj2":{"name:name","value:10"},"objone":{"name:name","value:10"}}]

But I need to change the property name alone and not the order, and I also try string replace but I think it is not the proper way, so please suggest me some ideas. 但是我需要单独更改属性名称而不是顺序,并且我也尝试替换字符串,但是我认为这不是正确的方法,因此请提出一些建议。

Objects have no order. 对象没有顺序。 Any apparent order you see is unspecified behavior and you cannot rely on it. 您看到的任何明显的顺序都是未指定的行为,您不能依靠它。 They didn't when the question was asked, but they do now : 他们不是在问问题时提出的,但是现在他们做了

  1. Let keys be a new empty List. 成为一个新的空列表。
  2. For each own property key P of O that is an integer index, in ascending numeric index order 对于O的每个自己的属性键P (它是整数索引),以数字索引的升序排列
    • Add P as the last element of keys . P添加为key的最后一个元素。
  3. For each own property key P of O that is a String but is not an integer index, in property creation order 对于每个自己的属性键P of O (按字符串创建,但不是整数索引),按属性创建顺序
    • Add P as the last element of keys . P添加为key的最后一个元素。
  4. For each own property key P of O that is a Symbol, in property creation order 对于每个自己的符号O的属性键P (按属性创建顺序)
    • Add P as the last element of keys . P添加为key的最后一个元素。
  5. Return keys . 返回

Your way of renaming the property is the only way of doing it: Creating a new one, then removing the old one. 重命名属性的方法是唯一的方法:创建一个新属性,然后删除旧属性。 Doing that will change where it appears in the order of the object, because it was created after the previous property. 这样做将改变它在对象顺序中的显示位置,因为它是在上一个属性之后创建的。

If you need order, use an array. 如果需要订购,请使用数组。 While theoretically arrays don't have order either (because they're not really arrays ), we have the convention that they have order, based on then numeric value of the indexes of the entries: The entry at index 0 is before the entry at index 1 and so on. 虽然理论上数组也不是有序的(因为它们不是真正的数组 ),但我们有一个约定,即它们有序,这取决于条目索引的数值:索引0处的条目位于处的条目之前索引1 ,依此类推。 (And modern JavaScript engines can and do use real arrays where possible.) (并且现代JavaScript引擎可以并且确实在可能的情况下使用实数组。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM