【问题标题】:JS - Sorting child objects within an objectJS - 对对象内的子对象进行排序
【发布时间】:2023-03-21 01:31:01
【问题描述】:

我正在尝试查找是否有一种方法可以使用 bool 值对对象中的对象进行排序。我一直无法找到任何帮助,甚至不确定是否可能。

我的对象示例是这样的:

{
"Music": {
    "Key": "Music",
    "Title": "Music",
    "Icon": "t-music",
    "Colour": "blue",
    "Active": false
},
"The Arts": {
    "Key": "The Arts",
    "Title": "The Arts",
    "Icon": "t-arts",
    "Colour": "blue",
    "Active": false
},
"Social": {
    "Key": "Social",
    "Title": "Social",
    "Icon": "t-social",
    "Colour": "yellow",
    "Active": true
}

}

是否有根据“Active”布尔值对父对象中的这些对象进行排序?

【问题讨论】:

  • 对象没有顺序
  • 您可以通过Object.keys(yourObj).sort(...) 获取显示密钥的顺序

标签: javascript boolean


【解决方案1】:

虽然对象没有排序顺序,但您可以根据 Active 布尔值将这些对象组织到一个数组中。使用.sort().map()

var obj = {
  "Music": {
    "Key": "Music",
    "Title": "Music",
    "Icon": "t-music",
    "Colour": "blue",
    "Active": false
  },
  "The Arts": {
    "Key": "The Arts",
    "Title": "The Arts",
    "Icon": "t-arts",
    "Colour": "blue",
    "Active": true
  },
  "Social": {
    "Key": "Social",
    "Title": "Social",
    "Icon": "t-social",
    "Colour": "yellow",
    "Active": true
  }
};

var sorted = Object.keys(obj) // ["Music", "The Arts", "Social"]
  .sort(function(a, b) {
    return obj[b].Active - obj[a].Active; // Organize the category array
  })
  .map(function(category) {
    return obj[category]; // Convert array of categories to array of objects
  });

【讨论】:

  • 更好的obj[b].Active - obj[a].Active,因为它处理obj[b].Active === obj[a].Active的情况
【解决方案2】:

对象中不存在顺序的概念,但您可以通过将元素转换为数组、对其进行排序并从中创建新对象来直观地打乱条目。

您可以使用Array#sort 并传递一个函数从嵌套值排序。

let arr = Object.entries(obj).sort(([key1, val1], [key2, val2]) => val2.Active)

arrayToObject = array => {
  let newObj = {}
  array.forEach(([key, val]) => {
    newObj[key] = val
  })
  return newObj
}

console.log(arrayToObject(arr))

// { Social: 
//   { Key: 'Social',
//     Title: 'Social',
//     Icon: 't-social',
//     Colour: 'yellow',
//     Active: true },
//   Music: 
//   { Key: 'Music',
//     Title: 'Music',
//     Icon: 't-music',
//     Colour: 'blue',
//     Active: false },
//   'The Arts': 
//   { Key: 'The Arts',
//     Title: 'The Arts',
//     Icon: 't-arts',
//     Colour: 'blue',
//     Active: false } }

【讨论】:

    【解决方案3】:

    谢谢各位,

    我不确定是否可以对对象进行分类,但问一下也无妨。

    Borja 的回答对我有用,但只有一次我使用 Thomas 的 'obj[b].Active - obj[a].Active' 代替 '!obj[a].Active && obj[b].Active' .

    我刚刚看到了 Andrew 的回复,并将对其进行测试。

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 2015-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多