Sort the keys of an object simulating ORDER BY ASC NAME

3

In mysql on the command SELECT * FROM minha-tabela ORDER BY nome ASC the list will be returned with all results sorted in ascending order based on column nome , I would like to know how I can do the same with a js object; Example:

Object
   1: Object
      nome: "Batista"
   2: Object
      nome: "Thiago"
   3: Object
      nome: "Joana"
   4: Object
      nome: "Ana"

What would be the function to reorder the keys of my object alphabetically based on the nome column so that it would look like this:

Object
   1: Object
      nome: "Ana"
   2: Object
      nome: "Batista"
   3: Object
      nome: "Joana"
   4: Object
      nome: "Thiago"
    
asked by anonymous 05.01.2017 / 23:42

1 answer

2

By sort command by doing the following:

var obj = [{nome: "Batista"}, {nome: "Thiago"},
           {nome: "Joana"},{nome: "Ana"}];

//console.log(obj); // antes

obj.sort(function(a, b){
    var aa = a.nome.toLowerCase();
    var bb = b.nome.toLowerCase(); 
    if(aa < bb) return -1;
    if(aa > bb) return 1;
    return 0;
});

console.log(obj); // depois

References:

05.01.2017 / 23:51