Sort an object’s keys by simulating ORDER BY ASC NAME

Asked

Viewed 341 times

3

In mysql in command SELECT * FROM minha-tabela ORDER BY nome ASC the list will be returned with all results ordered ascendingly based on the column nome, i wonder 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 my object keys alphabetically based on the column nome to keep it that way:

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

1 answer

3


By command Sort making the comparison as follows:

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

If in the particular case it is an object with several objects inside, example:

{0: {name:'a'}, 1: {name:'c'}, 2: {name:'b'}}

has the way to take these values and transform into array with Object.values and apply the same procedure with the sort, after all is a array:

var obj = {0: {name:'a'}, 1: {name:'c'}, 2: {name:'b'}};

var objAsc = Object.values(obj).sort((a,b) => {
 if (a.name<b.name) return -1;
 if (a.name>b.name) return 1;
 return 0; 
});

console.log(objAsc);

References:

  • Does this work for Objects? Because I’m testing here and it says Object.Sort is not a Function, or I have to convert my Object to array?

  • Can you show @Leoletto your code in full? In my example is a array of objects

  • I think there is the problem, because mine is not an array of objects, but an object with other objects inside

  • @Leoletto I want to see this object has how to put, maybe it’s a trivial setting where the ordination is, please post it for me to see!

  • This is my real Object the keys must be reordered according to the title marked on the image: http://imgur.com/a/5gGPr

  • Converting the main object to an array and applying its function worked perfectly.

  • I understand that this answer fits your case @Leoletto. In the case, in the end, just turn the array into object. Because the only solution to sort objects is to transform the keys into array and then return to the original converted ones (to sort the keys of an obj for example).

  • @Leoletto are several keys and within several object arrays, if you need to order all?

  • Yes, but turning the main object into an array and applying its function worked well : http://imgur.com/a/6Dn8n

  • Poxa @Leoletto truth now straight funfo.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.