如何通过特定键对json对象进行排序

时间:2020-08-14 17:01:25

标签: javascript arrays json sorting object

我有这个JSON数据,不确定如何调用它,因为JavaScript对象vs JavaScript数组vs JSON字符串使我非常困惑。

     {  'slot': 1, url: 'http://example.com'},
     {  'slot': 2, url: 'http://example.com'},
     {  'slot': 3, url: 'http://example.com'},
     {  'slot': 1, url: 'http://example.com'},
     {  'slot': 2, url: 'http://example.com'},
     {  'slot': 3, url: 'http://example.com'},
     {  'slot': 4, url: 'http://example.com'},

是否有一种简单的方法可以按我的slot值对它进行排序,使它变成这样:?

     {  'slot': 1, url: 'http://example.com'},
     {  'slot': 1, url: 'http://example.com'},
     {  'slot': 2, url: 'http://example.com'},
     {  'slot': 2, url: 'http://example.com'},
     {  'slot': 3, url: 'http://example.com'},
     {  'slot': 3, url: 'http://example.com'},
     {  'slot': 4, url: 'http://example.com'},

我可能可以通过循环并创建对象/数组的副本来做到这一点,但是也许为此有一些预定义的sort()函数?

2 个答案:

答案 0 :(得分:2)

    let ToSort = [
  { slot: 1, url: "http://example.com" },
  { slot: 2, url: "http://example.com" },
  { slot: 3, url: "http://example.com" },
  { slot: 1, url: "http://example.com" },
  { slot: 2, url: "http://example.com" },
  { slot: 3, url: "http://example.com" },
  { slot: 4, url: "http://example.com" },
];

 ToSort.sort(function(a, b){
   return a.slot - b .slot
 })
 console.log(ToSort)

答案 1 :(得分:1)

下面的代码段应该会对您有所帮助

const data = [
  { slot: 1, url: "http://example.com" },
  { slot: 2, url: "http://example.com" },
  { slot: 3, url: "http://example.com" },
  { slot: 1, url: "http://example.com" },
  { slot: 2, url: "http://example.com" },
  { slot: 3, url: "http://example.com" },
  { slot: 4, url: "http://example.com" },
]

function compare(a, b) {
  if (a.slot < b.slot) {
    return -1
  }
  if (a.slot > b.slot) {
    return 1
  }
  return 0
}

data.sort(compare)

console.log(data)