如何对打字稿中的Json对象进行排序

时间:2019-04-18 13:24:36

标签: json angular sorting

我想在我的角度应用程序中对json对象进行排序。

此json对象如下所示:

{"9 - ABCDEF":{"isSucceeded":true},
"18 - Remote Software Update":{"isSucceeded":true,},
"4 - n.a."{"isSucceeded":true,}}

我只是像这样对json对象进行排序:

{"4 - ABCDEF":{"isSucceeded":true},
"9 - Remote Software Update":{"isSucceeded":true,},
"18 - n.a."{"isSucceeded":true,}}

有人知道一些解决方案吗? 我听说过underscore.js 有人可以给我一些例子吗

最好的问候,

狮子座

1 个答案:

答案 0 :(得分:0)

尝试类似的事情:

使用forEach

const object = {
   "18 - n.a.": {"isSucceeded":true,},
   "4 - ABCDEF": {"isSucceeded":true},
   "9 - Remote Software Update": {"isSucceeded":true,},
};
const ordered = {};
const firstNumber = str => parseInt(str.split(' -')[0].trim());
Object.keys(object)
.sort((a, b) => firstNumber(a) > firstNumber(b) ? 1 : -1)
.forEach(function(key) {
   ordered[key] = object[key];
});

console.log(ordered);

使用reduce函数:

const object = {
   "18 - n.a.": {"isSucceeded":true,},
   "4 - ABCDEF": {"isSucceeded":true},
   "9 - Remote Software Update": {"isSucceeded":true,},
};
const firstNumber = str => parseInt(str.split(' -')[0].trim());
const ordered = Object.keys(object)
.sort((a, b) => firstNumber(a) > firstNumber(b) ? 1 : -1)
.reduce((acc, key) => {
   acc[key] = object[key];
   return acc;
}, {});

console.log(ordered);