Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the javascript object property name dynamically

I have created a JavaScript object like

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

I need to change the old_name to 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:

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.

like image 634
Troy Avatar asked Oct 20 '14 08:10

Troy


1 Answers

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
    • Add P as the last element of keys.
  3. For each own property key P of O that is a String but is not an integer index, in property creation order
    • Add P as the last element of keys.
  4. For each own property key P of O that is a Symbol, in property creation order
    • Add P as the last element of keys.
  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. (And modern JavaScript engines can and do use real arrays where possible.)

like image 56
T.J. Crowder Avatar answered Oct 29 '22 16:10

T.J. Crowder