According to proxima-b, there is no deterministic way to order an object.
However, you can create a helper function that allows you to specify the order in which key/value pairs are displayed. The beauty of Typescript is that you can achieve this in a type-safe manner!
const myObject = {
'hello3': 'Value 3',
'hello1': 'Value 1',
'hello2': 'Value 2',
'hello4': 'Value 4',
} as const;
function orderObjectToArrayKeyValue<Obj>(obj: Obj, orderKeys: { [key in keyof Obj]: number }): { key: keyof Obj, value: Obj[keyof Obj] }[] {
return Object
.entries<number>(orderKeys)
.sort(([, order1], [, order2]) => order1 < order2 ? -1 : 1)
.map(([key]) => ({ key, value: obj[key as keyof Obj] }) as { key: keyof Obj, value: Obj[keyof Obj] });
}
For example, if you use the following:
console.log(orderObjectToArrayKeyValue(myObject, {
hello1: 1,
hello2: 2,
hello3: 3,
hello4: 4,
}));
You will receive:
[
{
"key": "hello1",
"value": "Value 1"
},
{
"key": "hello2",
"value": "Value 2"
},
{
"key": "hello3",
"value": "Value 3"
},
{
"key": "hello4",
"value": "Value 4"
}
]
Using your preferred framework, it's simple to iterate over this array and display the values (and optionally use the keys).
Check out the live example (press enter while focusing the left side and it'll run the code, the output will be displayed in your console).