Home > Software engineering >  What should I do to sort an object by name ascending and descending
What should I do to sort an object by name ascending and descending

Time:06-30

I have tried to find a solution and could find something that is close but not there yet. Javascript sort an object by keys based on another Array? I want to sort them by ABC ascending and descending and I don't know where to start.

const Accounts = {
  'thing': {
    password: '123',
  }
}

const sortedKeys = Object.getOwnPropertyNames(Accounts).sort();
//This returns the names but not the passwords

CodePudding user response:

If I understood your question correctly, then it's essentially a duplicate of this question.

From the linked question's comments: "The ordering of object properties is non-standard in ECMAScript", so you can't do what you want to do directly.

Here's how I'd do it:

const Accounts = {
  'thing': {
    password: '123',
  }
} 

//get array keys and sort them
let sorted_keys = Object.keys(Accounts).sort();

//if you need your values too then use keys to access
sorted_keys.forEach(function(key) {//access each key and map to its value
    let value = Accounts[key]
    //do whatever with value
}

CodePudding user response:

const sortedKeys = Object.getOwnPropertyNames(Accounts).sort();

The above sortedKeys will contain an array of sorted keys as you have seen. You can then map the sorted keys to their values and have a sorted object.

The code is a simpler version of what I just explained:

const Accounts = {
  thing: { password: "123 }
}

const sortedAccounts = Object.keys(Accounts)
  .sort()
  .reduce((accumulator, key) => {
    accumulator[key] = obj[key];

    return accumulator;
  }, {});

  • Related