考虑json格式的对象数组,如下所示,
[
{_id: "acd", employee: "jack"},
{_id: "sdd", employee: "Monica", timeTaken: 0.6},
{_id: "eee", employee: "Rose", timeTaken: 0.6, task: "GST"},
]
我很想简单地根据对象中的键数对对象数组进行排序。如果对象具有最大数量的键,则它必须位于顶部。
预期结果如下,
[
{_id: "eee", employee: "Monica", timeTaken: 0.6, task: "GST"},
{_id: "sdd", employee: "Monica", timeTaken: 0.6},
{_id: "acd", employee: "jack"},
]
任何帮助都将受到高度赞赏:)
答案 0 :(得分:1)
使用sort
根据对象中的键数对对象数组进行排序。
var arr = [
{_id: "acd", employee: "jack"},
{_id: "sdd", employee: "Monica", timeTaken: 0.6},
{_id: "eee", employee: "Rose", timeTaken: 0.6, task: "GST"},
];
arr.sort(function(a,b){
return Object.keys(b).length - Object.keys(a).length;
});
console.log(arr);