skip to Main Content

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


  1. 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

    const arr = [
      {
        "0%": 1,
      },
      {
        "5%": 1,
      },
      {
        "05%": 1,
      },
      {
        "6%": 1,
      }
    ];
    
    const obj = {};
    const order = [];
    
    for (const item of arr) {
      const key = Object.keys(item)[0];
      obj[key] = item[key];
      order.push(key);
    }
    
    for (const key of order) {
      console.log(key, obj[key]);
    }

    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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search