search

Home  >  Q&A  >  body text

javascript - How to sort this object

var obj = {
    "10": 20.1,
    "11": 16,
    "12": 12.7,
    "01": 0,
    "02": 0,
    "03": 0,
    "04": 0,
    "05": 0,
    "06": 0,
    "07": 0,
    "08": 27.6,
    "09": 24.3
};

Sort by key value.

巴扎黑巴扎黑2749 days ago770

reply all(5)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-06-30 10:01:25

    JSON is unordered, and the browser will automatically sort according to key, so sorting is useless.

    ,

    reply
    0
  • 欧阳克

    欧阳克2017-06-30 10:01:25

    It is recommended to convert to array first, then sort, and then convert to object

    reply
    0
  • 欧阳克

    欧阳克2017-06-30 10:01:25

        var obj = {
          '10': 20.1,
          '11': 16,
          '12': 12.7,
          '01': 0,
          '02': 0,
          '03': 0,
          '04': 0,
          '05': 0,
          '06': 0,
          '07': 0,
          '08': 27.6,
          '09': 24.3
        }
        console.log(Object.keys(obj).sort().reduce((a, b) => (a[b] = obj[b], a), {}))

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-30 10:01:25

    var arr = []
    for (const key in obj) {
      arr[key] = obj[key]
    }

    This can achieve your needs

    If the middle is not continuous, you need to filter it again later

    reply
    0
  • 阿神

    阿神2017-06-30 10:01:25

    Why do objects need to be sorted? Can’t we get the setting value directly through the key value?

    reply
    0
  • Cancelreply