我有一个对象数组:
[
{
"Accept Credit Cards":"17",
"Take-Out":"17",
"Alcohol":"16",
"Caters":"10",
"Takes Reservations":"11",
"Smoking":"0",
"Dogs Allowed":"1",
"Outdoor Seating":"12",
"Coat Check":"0",
"Waiter Service":"14",
"Wi-Fi":"10",
"Good For Groups":"16",
"Wheelchair Accessible":"13"
}
]
我想根据价值对此进行排序。所以我的结果应该是这样的:
[
{
"Accept Credit Cards":"17",
"Take-Out":"17",
"Alcohol":"16",
"Good For Groups":"16",
"Wheelchair Accessible":"13"
AND SO ON.....
}
]
我将如何做到这一点?我试了一下。但这只是基于密钥进行排序。任何指针都赞赏。
答案 0 :(得分:3)
正如RyanZim在评论中提到的那样,排序对象的属性并不是真正的目的。 JavaScript不保证属性顺序,因此您不应该依赖它们。但是,您可以创建一个属性数组,并根据对象中的值对它们进行排序。
const arr = [
{
"Accept Credit Cards":"17",
"Take-Out":"17",
"Alcohol":"16",
"Caters":"10",
"Takes Reservations":"11",
"Smoking":"0",
"Dogs Allowed":"1",
"Outdoor Seating":"12",
"Coat Check":"0",
"Waiter Service":"14",
"Wi-Fi":"10",
"Good For Groups":"16",
"Wheelchair Accessible":"13"
}
];
const sorted = Object.keys(arr[0]).sort((a, b) => arr[0][b] - arr[0][a]);
sorted.forEach(x => console.log(x + ': ' + arr[0][x]));

如果你想变得更加漂亮并按字母顺序排序:
const arr = [
{
"Accept Credit Cards":"17",
"Take-Out":"17",
"Alcohol":"16",
"Caters":"10",
"Takes Reservations":"11",
"Smoking":"0",
"Dogs Allowed":"1",
"Outdoor Seating":"12",
"Coat Check":"0",
"Waiter Service":"14",
"Wi-Fi":"10",
"Good For Groups":"16",
"Wheelchair Accessible":"13"
}
];
const sorted = Object.keys(arr[0]).sort((a, b) => {
if (arr[0][a] > arr[0][b]) return -1;
if (arr[0][a] < arr[0][b]) return 1;
if (a > b) return 1;
if (a < b) return -1;
return 0;
});
sorted.forEach(x => console.log(x + ': ' + arr[0][x]));
&#13;