gpt4 book ai didi

javascript - JS - 对对象内的子对象进行排序

转载 作者:行者123 更新时间:2023-11-29 21:00:26 26 4
gpt4 key购买 nike

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

我的对象示例是这样的:

{
"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” boolean 值对父对象中的这些对象进行排序?

最佳答案

虽然对象没有排序顺序,但您可以根据 Active boolean 值将这些对象组织在一个数组中。使用 .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
});

关于javascript - JS - 对对象内的子对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46780601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com