1

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,
}
  • `Object.fromEntries(arr.map(e => Object.entries(e)[0]))`? `new Map(arr.map(e => Object.entries(e)[0]))` to prserve order – cmgchess May 04 '23 at 10:37
  • Do you really need an object or an associative array? What is the expected behaviour in case you assign a duplicate key? – Biller Builder May 04 '23 at 12:44

1 Answers1

1

You don't need to do anything, it already works that way

var obj: { [k: string]: any } = {};
obj["0%"] = 1
obj["**5%**"] = 1
obj["05%"] = 1
obj["6%"] = 1
console.log(Object.keys(obj))
// [LOG]: ["0%", "**5%**", "05%", "6%"] 

It's just console showing items in a-z order rather then actual order

Does JavaScript guarantee object property order?
Current Language Spec (since ES2015) insertion order is preserved, except in the case of keys that parse as positive integers (eg "7" or "99"), where behavior varies between browsers. For example, Chrome/V8 does not respect insertion order when the keys are parse as numeric.

Dimava
  • 7,654
  • 1
  • 9
  • 24
  • This is implementation-dependant behaviour and therefore must not be relied upon. If you need a data structure with ordered keys, only `Array`/`Map`/`Set` derivatives can provide it. – Biller Builder May 04 '23 at 12:52
  • Yeah, objects are hash tables for the optimization purposes of the engine. But once you start to deal with such objects in serializable contexts such as JSON (in which it will be converted to a plain JSON object), this behaviour become irrelevant and the order of keys depends on the serializer/deserializer implementation. So it must not be relied upon unless you can ensure all potential consumers of this data can serialize/deserialize it while preserving the key order. – Biller Builder May 04 '23 at 13:06