Sort array of objects by key name

I need to sort the keys to an exact order, for example I have the next array:

const arr = [
             {
               active: true,
               code: "1234",
               indentifier: "OPC-999",
               name: "Example",
               start: "02-12-1997",
             }
             {
               active: false,
               code: "4567",
               indentifier: "OPC-111",
               name: "Example",
               start: "03-02-2010",
             }
]

The exact order for every object should be: name, indentifier, code, start, active.

I don’t need to sort by value but by key name.

What’s the best way to do this?

Answer

for (i = 0; i < arr.length; i++) {
  arr[i] = {
    name: arr[i].name,
    indentifier: arr[i].indentifier,
    code: arr[i].code,
    start: arr[i].start,
    active: arr[i].active,
  }
}

After doing this, your arr will be sorted as you wanted:

[
  {
    "name": "Example",
    "indentifier": "OPC-999",
    "code": "1234",
    "start": "02-12-1997",
    "active": true
  },
  {
    "name": "Example",
    "indentifier": "OPC-111",
    "code": "4567",
    "start": "03-02-2010",
    "active": false
  }
]

Leave a Reply

Your email address will not be published. Required fields are marked *