我想在Javascript中对JSON进行排序

时间:2017-11-08 15:55:30

标签: javascript json sorting

我有一个以下JSON需要按字母顺序排序(基于值),

{ 
   1: "Your Professional",
   2: "Describing Clothes", 
   3: "Describing People", 
   4: "At the Doctor", 
   5: "At the supermarket", 
   6: "Cooking", 
   7: "After work", 
   8: "Describing Objects and Places", 
   9: "Asking Questions", 
  10: "A city tour" 
}

JSON按键排序,但我想按字母顺序用value对其进行排序。

我的期望(根据value排序),

{ 
   10: "A city tour", 
   7: "After work", 
   9: "Asking questions", 
   4: "At the Doctor", 
   5: "At the supermarket", 
   6: "Cooking", 
   2: "Describing clothes", 
   8: "Describing Objects and Places", 
   3: "Describing People", 
   1: "Your Professional"
}

如果有人指导我,这将非常有帮助。

2 个答案:

答案 0 :(得分:4)

如果您有权访问后端,我会将其作为数组发送,因为JSON未排序。

但是,如果您必须在客户端上执行此操作:

const myJSON = {1: 'Key one', 2: 'Key two'}
const sorted = Object.keys(myJSON)
  .map(Number)
  .sort((a, b)=> b - a)
  .map(item=> {
    const obj = {}
    obj[item] = myJSON[item]
    return obj
  })

如果你可以使用数组,那就

.map(item => myJSON[item])

答案 1 :(得分:1)

来自sort() documentation on MDN

var items = [
  { name: "Edward", value: 21 },
  { name: "Sharpe", value: 37 },
  { name: "And", value: 45 },
  { name: "The", value: -12 },
  { name: "Magnetic", value: 13 },
  { name: "Zeros", value: 37 }
];
items.sort(function (a, b) {
  return a.value - b.value;
});

所以让我们把它翻译成你的用例:

const objFromJson = { 
   1: "Your Professional",
   2: "Describing Clothes", 
   3: "Describing People", 
   4: "At the Doctor", 
   5: "At the supermarket", 
   6: "Cooking", 
   7: "After work", 
   8: "Describing Objects and Places", 
   9: "Asking Questions", 
  10: "A city tour" 
}
let ar = []

// convert your object into an array of objects
for (const key in objFromJson) {
  ar.push({ id: key, value: objFromJson[key] })
}

console.log(ar)

// sort by value
ar.sort(function (a, b) {
  return a.value > b.value;
});

console.log(ar)