Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

322
Visualizações
What should I do to sort an object by name ascending and descending

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
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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;
  }, {});

about 4 years ago · Juan Pablo Isaza Relatório

0

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
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda