How to order an object according to its key?

1

I have an object that I need to sort, I'm interested in defining the order of about 4 at least the others could be ordered as they are, saying that this object does not always come in the same order is therefore my query.

{ 
  gratificacionZona:7500 //Quinto
  leyNoDocente:"28000" 
  sueldoBase:50000 //Primero
  sueldoGeneral:0 //Segundo
  sueldoPIE:0   //Tercero
  sueldoSEP:0  //Cuarto
}

Sometimes this object can bring more parameters, but I'm only interested in the order of these marked.

this code enters the items to the fix that I need.

   _.forEach(liquidacion.imponible, function(value,key){
                aa.table.body.push([{ text: key , border: [true, false, false, false] }, { text: value , border: [false, false, true, false] }]);

            })
    
asked by Luis Ruiz Figueroa 07.10.2017 в 18:03
source

2 answers

2

Using ES6:

let objeto = { 
  gratificacionZona:7500,
  leyNoDocente:"28000", 
  sueldoBase:50000, //Primero
  sueldoGeneral:0, //Segundo
  sueldoPIE:0,   //Tercero
  sueldoSEP:0  //Cuarto
}

objeto = {
  sueldoBase:objeto.sueldoBase, //Primero
  sueldoGeneral:objeto.sueldoGeneral, //Segundo
  sueldoPIE:objeto.sueldoPIE,   //Tercero
  sueldoSEP:objeto.sueldoSEP,  //Cuarto
  ...objeto
}

console.log(objeto)

From the old way (BabelJS through):

"use strict";

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var objeto = {
  gratificacionZona: 7500,
  leyNoDocente: "28000",
  sueldoBase: 50000, //Primero
  sueldoGeneral: 0, //Segundo
  sueldoPIE: 0, //Tercero
  sueldoSEP: 0 //Cuarto
};

objeto = _extends({
  sueldoBase: objeto.sueldoBase, //Primero
  sueldoGeneral: objeto.sueldoGeneral, //Segundo
  sueldoPIE: objeto.sueldoPIE, //Tercero
  sueldoSEP: objeto.sueldoSEP }, objeto);
  
console.log(objeto)
    
answered by 07.10.2017 в 22:01
1

As such there is no way to sort the attributes of an object in javascript, for that you have to use certain functions or methods to achieve it:

Object.keys(data).sort()
  .forEach(function(item, i) {
      console.log(item, data[item]);
   });  // Donde data es tu objeto

This can be a form, when you order from highest to lowest, alphabetically, etc.

In your case, you would need a help list, which if you keep your order, like this:

let order = ['sueldoBase', 'sueldoGeneral', 'sueldoPIE', 'sueldoESP', 'gratificacionZona']
order.forEach(function(item, i) {
    console.log(item, data[item]);
});  // Donde data es tu objeto

Any questions comment. Source

    
answered by 07.10.2017 в 18:39