【问题标题】:How to sort array of objects with unique keys by nested object value [closed]如何通过嵌套对象值对具有唯一键的对象数组进行排序[关闭]
【发布时间】:2021-02-04 13:37:56
【问题描述】:

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

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

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

【问题讨论】:

  • 请添加您的尝试。
  • arr.sort((a,b)=>(Object.values(b)[0].type==="array")-(Object.values(a)[0].type==="array"))
  • @gorak 我不知道 Object.values,这是完美的,谢谢。 IDK 如何将您的答案标记为正确
  • @AlecSelinger 我在 Gorak 评论的时候给你写了一个答案......

标签: javascript sorting


【解决方案1】:

像这样

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)

【讨论】:

    猜你喜欢
    • 2019-05-13
    • 2011-07-01
    • 2018-02-08
    • 2021-09-19
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 2012-02-08
    相关资源
    最近更新 更多