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

94
Vistas
sorting an object by value type

I am trying to sort an Object from

{"key4": {"name":"joe"},"key3": ["aaa", "bbb"],"key5": {"aaa":["name","joe"]}, "key1": "TypeString", "key2": 0}

to

{"key1": "TypeString", "key2": 0, "key3": ["aaa","bbb"], "key4": {"name":"joe"},"key5": {"aaa":["name","joe"]}}

my main goal is to sort by the value type and not the the value its self.. ie each value with the type string comes first followed by int then arrays and final object.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

When you print an object, the order of keys is implementation dependent. If you really need to get the keys in insertion order, you can use Reflect.ownKeys() (for details, see MDN):

const obj = {"key4": {"name":"joe"},"key3": ["aaa", "bbb"],"key5": {"aaa":["name","joe"]}, "key1": "TypeString", "key2": 0};

const keys = Object.keys(obj);
const keysSorted = keys.sort((key1, key2) => getTypeSortId(obj[key1]) - getTypeSortId(obj[key2]));
const objSorted = keysSorted.reduce((o, key) => (o[key] = obj[key], o), {});
console.log(objSorted);
console.log(Reflect.ownKeys(objSorted));

function getTypeSortId(value) {
  return (
    typeof value === "string" ? 1 :
    typeof value === "number" ? 2 :
    value instanceof Array ? 3 :
    typeof value === "object" ? 4 :
    5
  );
}

about 4 years ago · Juan Pablo Isaza Denunciar
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