gpt4 book ai didi

javascript - 对嵌套在嵌套在另一个对象中的对象中的数组进行排序

转载 作者:行者123 更新时间:2023-11-30 16:35:54 25 4
gpt4 key购买 nike

我有一个名为“团队”的对象,每个团队名称都有一组嵌套对象。在那个团队名称中,我有球员,我希望对每个数组进行动态排序,而不是为每个团队进行排序。xxxx.player.sort();

var team = {
fnatic: {
team: "Fnatic",
player: ["Olofmeister", "JW", "Pronax", "Krimz", "Flusha"]
},
titan: {
team: "Titan",
player: ["Ex6Tenz", "shox", "RpK", "SmithZz", "Maniac"]
},
nip: {
team: "Ninjas in Pyjamas",
player: ["GeT_RiGhT", "f0rest", "allu", "friberg", "XizT"]
},
nv: {
team: "EnVy Us",
player: ["kennyS", "apeX", "NBK-", "Happy", "kioShiMa"]
},

vp: {
team: "Virtus Pro",
player: ["PashaBiceps", "Taz", "byali", "Snax", "Xx"]
}
};

我正在尝试按字母顺序对玩家数组进行排序 (team.XXXX.player)。我发现我可以通过键入来做到这一点

team.fnatic.player.sort();

对于每个单独的团队,但我想迭代该对象,因为我将有大量的团队和球员需要排序。

感谢Arne Martin Aurlien on his blog and his object sort function这与我在这里搜索和阅读的内容一样接近:

for (var obj in team) {
if (team.hasOwnProperty(obj)) {
console.log(obj, team[obj].player); //line 107
[obj].player = sortObj(team[obj].player);
console.log(obj, team[obj].player); //line 109
}
}

不幸的是,这仍然只打印出未排序的数组:

fnatic ["Olofmeister", "JW", "Pronax", "Krimz", "Flusha"] script.js:107
fnatic ["Olofmeister", "JW", "Pronax", "Krimz", "Flusha"] script.js:109
titan ["Ex6Tenz", "shox", "RpK", "SmithZz", "Maniac"] script.js:107
titan ["Ex6Tenz", "shox", "RpK", "SmithZz", "Maniac"] script.js:109
...etc for each team

我觉得我在这里缺少一些简单的东西。谁能帮帮我?

最佳答案

使用Array.prototype.forEach在团队键上:

Object.keys(team).forEach(function(key) {
team[key].player.sort();
});

排序到位(mdn):

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

关于javascript - 对嵌套在嵌套在另一个对象中的对象中的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32704602/

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