基于键的降序对象

时间:2018-10-16 19:15:37

标签: javascript json

我正在使用一些API,它们以以下格式返回json,问题是它们将密钥作为浮点数发送。我无法修改其后端部分以制作正确的json。因此,我正在寻找quickfix以按降序显示以下数据。

220: {CE: {…}, PE: {…}}
225: {CE: {…}, PE: {…}}
230: {CE: {…}, PE: {…}}
235.23: {CE: {…}, PE: {…}}
240.32: {CE: {…}, PE: {…}}
245: {CE: {…}, PE: {…}}
250: {CE: {…}, PE: {…}}
255.12: {CE: {…}, PE: {…}}

我想按降序反转它,我试图弄清楚过去3个小时该怎么做。

我尝试了以下代码

function reverseObject(object) {
        var newObject = {};
        var keys = [];
        for (var key in object) {
            keys.push(key);
        }
        for (var i = keys.length - 1; i >= 0; i--) {

          var value = object[keys[i]];
          newObject[keys[i]]= value;
        }       

        return newObject;
      }

2 个答案:

答案 0 :(得分:1)

这将使用Object.entries()Array.prototype.sort()创建一个元组[['255.12', {CE: {…}, PE: {…}}],['250', {CE: {…}, PE: {…}}], …]数组:

function entriesDescending (object) {
  return Object
    .entries(object)
    .sort(([a], [b]) => b - a)
}

答案 1 :(得分:0)

const response = {
  220: {CE: 'foo', PE: 'bar'},
  225: {CE: 'foo', PE: 'bar'},
  230: {CE: 'foo', PE: 'bar'},
  235.23: {CE: 'foo', PE: 'bar'},
  240.32: {CE: 'foo', PE: 'bar'},
  245: {CE: 'foo', PE: 'bar'},
  250: {CE: 'foo', PE: 'bar'},
  255.12: {CE: 'foo', PE: 'foo'},
}

const fromEntries = (acc, [key, value]) => ({...acc, [key]: value})

const byNumberKey = ([a], [b]) => a - b

const sortKeys = obj =>
  Object.entries(obj)
    .sort(byNumberKey)
    .reduce(fromEntries, {})
  
console.log(
  sortKeys(response)
)