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.
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:
- Let keys be a new empty List.
- 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.
- 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.
- For each own property key P of O that is a Symbol, in property creation order
- Add P as the last element of keys.
- 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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With