-2

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?

9
  • Why do you need them to be in a specific order? Commented Mar 8, 2021 at 22:33
  • The component I'm trying to use needs me to put them in order Commented Mar 8, 2021 at 22:34
  • I don't think objects have a sense of order. Commented Mar 8, 2021 at 22:36
  • Can you share the component's code, then? Commented Mar 8, 2021 at 22:36
  • 1
    Then Javascript sort an object by keys based on another Array? since apparently copy-paste-ability is key... Commented Mar 8, 2021 at 22:45

2 Answers 2

1
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
  }
]
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a keys array with the object keys in your desired order. Then you can map each object in the array, generating a new object with properties created in the order defined in the keys 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",
             }
]

const keys = ['name', 'indentifier', 'code', 'start', 'active'];

const result = arr.map(o => Object.fromEntries(keys.map(k => [k, o[k]])));

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.