如何根据嵌套的对象值对具有唯一键的对象数组进行排序



真的很难找到解决方案。我有以下数据:

var arr = [
{ Main: {type: "object", ...} }
{ Poller: {type: "object", ...} }
{ connection: {type: "array", ...} }
{ Profile1: {type: "array", ...} }
{ Sender: {type: "object", ...} }
{ Profile2: {type: "array", ...} }
];

我的目标是生成一个数组,它首先列出type: array的对象。我尝试了sort()方法的各种实现,但不知道如何解释每个嵌套对象都有自己的键。任何帮助都是感激的

像这样

var arr = [
{ Main:       {type: "object",}},
{ Poller:     {type: "object",}},
{ connection: {type: "array" ,}},
{ Profile1:   {type: "array" ,}},
{ Func1:      {type: "function",}},
{ func2:      {type: "function",}},
{ Sender:     {type: "object",}},
{ Profile2:   {type: "array" ,}}
];
arr.sort((a, b) => {
if (Object.values(a)[0].type < Object.values(b)[0].type) return -1
if (Object.values(a)[0].type === Object.values(b)[0].type) return 0
if (Object.values(a)[0].type > Object.values(b)[0].type) return 1
})
console.log(arr)

最新更新