Home > Net >  sorting an object by value type
sorting an object by value type

Time:09-17

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.

CodePudding user response:

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
  );
}

  • Related