基于值对对象属性进行排序 [英] Sorting object properties based on value

查看:86
本文介绍了基于值对对象属性进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列对象:

[  
   {  
      "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"
   }
]

我想要根据值对此进行排序。所以我的结果应该是这样的:

I want to sort this based on the value. So my result should be something like:

[  
       {  
          "Accept Credit Cards":"17",
          "Take-Out":"17",
          "Alcohol":"16",
          "Good For Groups":"16",
          "Wheelchair Accessible":"13"
          AND SO ON.....

      }
]

我将如何做到这一点?我试了一下。但这只是基于密钥进行排序。任何指针都赞赏。

How will I do this? I tried a sort. But that just sorts based on the key. Any pointers appreciated.

推荐答案

正如RyanZim在评论中提到的那样,没有真正的目的来排序宾语。 JavaScript不保证属性顺序,因此您不应该依赖它们。但是,您可以创建一个属性数组,并根据对象中的值对它们进行排序。

As RyanZim has mentioned in the comments, there isn't really a purpose to sorting the properties of an object. JavaScript does not guarantee the property order, so you shouldn't rely on them being in order. You could, however, make an array of the properties and sort them based on the value in your object.

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

如果你想得到更好的并按价值排序那么按字母顺序:

If you want to get even fancier and sort by the value then alphabetically:

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

这篇关于基于值对对象属性进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆