正如proxima-b 所指出的,没有办法确定地对对象进行排序。
您可以做的是创建一个帮助函数,让您定义您希望显示键/值的顺序。 Typescript 最酷的地方在于你可以以一种类型安全的方式做到这一点!
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] });
}
用上面的例子,如果你调用:
console.log(orderObjectToArrayKeyValue(myObject, {
hello1: 1,
hello2: 2,
hello3: 3,
hello4: 4,
}));
你会得到
[
{
"key": "hello1",
"value": "Value 1"
},
{
"key": "hello2",
"value": "Value 2"
},
{
"key": "hello3",
"value": "Value 3"
},
{
"key": "hello4",
"value": "Value 4"
}
]
然后使用您选择的框架,遍历该数组并显示值将非常容易(+ 如果需要,请使用键)。
这是live example(在关注左侧的同时按下回车键,它将运行代码,输出将显示在您的控制台中)。