I need to create an object in dynamically add properties but keep the sequence of adding.
An example of the object I want to get:
var obj = {
"0%": 1,
"5%": 1,
"05%": 1,
"6%": 1,
}
The values can be different, but it is important to keep the sequence:
For example, I have an array:
var arr =[
{
"0%": 1,
},
{
"5%": 1,
},
{
"05%": 1,
},
{
"6%": 1,
}
]
How can I convert it to what I want?
I tried to do like this:
var obj: { [k: string]: any } = {};
obj["0%"] = 1
obj["**5%**"] = 1
obj["05%"] = 1
obj["6%"] = 1
but as a result I get:
var obj = {
"0%": 1,
"**05**%": 1,
"5%": 1,
"6%": 1,
}
2
Answers
The issue you’re facing is due to the fact that object properties in JavaScript are unordered.
Here is a new code that works well
In this code, we create an empty object obj and an empty array order. Then, we iterate over the items in arr, extract the key and value from each item, add the property to obj and push the key to the order array.
You don’t need to do anything, it already works that way
It’s just console showing items in a-z order rather then actual order