It gets an object with quite specific keys from the backend. I have to change some values but only to the property where I should break. However, I must keep the order.
The code below works, but I have a problem in my project – different browser? Don’t know. "For of" starts from key "14D". How can I be sure, how can I keep order? Because of specific keys, I cannot sort it.
let updatedData = {};
const dataFromBd = {
'1M': {
name: 'anna'
},
'1Y': {},
'2Y': {},
'3M': {},
'3Y': {},
'4Y': {},
'5Y': {},
'6M': {},
'7Y': {},
'10Y': {},
'14D': {},
'15Y': {},
'>20Y': {}
};
for (let [key, value] of Object.entries(dataFromBd)) {
updatedData[key] = 'hello';
if (key === '10Y') break;
}
console.log('data', updatedData);
If you need order, use an array, not an object. Or sometimes it can make sense to use a
Map
.Using object as you’re doing now
However –
That code will continue to work on any standard-complaint JavaScript engine as long as your keys are in the style that you’ve shown, but beware that the order for
Object.entries
is only very recently defined. JavaScript has had an order for object properties since ES2015, but it wasn’t until much more recently that that order was applied tofor-in
,Object.keys
,Object.values
, orObject.entries
.For properties whose names are non-integer-index strings, the order is the order of property creation. So since you’re creating the properties in the order you wan them, they’ll be in that order.
But: Relying on property order in this way is delicate and I don’t recommend it. For instance, if at some stage one of your property names becomes
"42"
instead of things like"1M"
, it will break because that’s an integer-index string property name, so its place in the order is not based on when it was created, it’s based on its numeric value.Here’s an example of that:
Using an array instead
Arrays are ordered, so of course using an array of objects will work reliably. Here’s the example above using an array of arrays (or it could be an array of objects with
key
andvalue
, etc.):Using a
Map
insteadUnlike objects, the order of entries in a
Map
is defined purely in order of insertion regardless of the value of the key. This guarantee has been present sinceMap
was introduced in ES2015.Here’s the example above using
Map
: