How to dynamically replace javascript object property name

I created a JavaScript object like

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

I need to change old_name to new_name . I tried

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

And it works, but the order of the objects changes.

For instance:

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

If you replace obj1 with objone as follows:

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

Property order changed to:

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

But I need to change the name of the property on my own, not the order, and I will also try replacing the string, but I think it is not, so please offer me some ideas.

+5
source share
1 answer

Objects have no order. Any visible order that you see is unspecified behavior, and you cannot rely on it. They did not ask a question, but now they do :

  • Let the keys be a new empty list.
  • For each eigenvalue of the P of O property, which is an integer index, in ascending order of the numerical index
    • Add P as the last element of the keys.
  • For each private key of a property P of O, which is a string but is not an integer index, in the order in which the property is created
    • Add P as the last element of the keys.
  • For each private key of the P of O property, which is a symbol, in the order the property was created
    • Add P as the last element of the keys.
  • Return keys.

Your way to rename a property is the only way to do this: create a new one and then delete the old one. The execution of this will change where it appears in the order of the object, because it was created after the previous property.

If you need an order, use an array. While theoretically arrays have no order (because they are not arrays ), we have a convention, they have an order based on then the numerical value of the record indices: the record at index 0 is in front of the entry with index 1 , etc. (And modern JavaScript mechanisms can and do use real arrays where possible.)

+5
source

Source: https://habr.com/ru/post/1205076/


All Articles