Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
Sort a key and value in a javascript object using ES6

I have an object whose keys are dynamically generated by the data receoved from the api response.

code:

var object = {
ABS-Test: 11,
CAS-tab-Running: 9,
ABS-tag-objetc: 9,
Internet-Facing-ABS: 9,
ABS-connector-test: 11
}

How can I sort using the object above based on value and key. Example of the expected output when sorted based on key of the object;

var sortedObject = {
    ABS-connector-test: 11,
    ABS-tag-objetc: 9,
    ABS-Test: 11,
    CAS-tab-Running: 9,
    Internet-Facing-ABS: 9
    }


var sortedValueObject = {
    ABS-tag-objetc: 9,
    CAS-tab-Running: 9,
    Internet-Facing-ABS: 9,
    ABS-connector-test: 11,
    ABS-Test: 11,
    }

I have referred Sort a JavaScript object by key or value; ES6 and SO far I have this for sorting by value:

sorted_object = Object.entries(unsorted_object)
  .sort(([,v1], [,v2]) => +v2 - +v1)
  .reduce((r, [k, v]) => Object.assign(r, { [k]: v }), {});

and this for sorting by key:

sorted_object = Object.entries(data)
  .sort((a, b) => a[1] - b[1])
  .reduce((a, [key, val]) => {
    a[key] = val;
    return a;
  }, {});

Both of them return output in certain order (either ascendeing or desc). Do we have a logic or a lodash method that'll help to toggle the sorting logic based on the asc or desc value provided?

I tried via the _orderBy() and _sortBy() from lodash Reactjs, however they require a static key value to be passed to get the results.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda