gpt4 book ai didi

javascript - 按键值重新排序 Json 数组

转载 作者:行者123 更新时间:2023-11-30 13:07:47 24 4
gpt4 key购买 nike

我有一个联系人列表,它以这种非常长的形式返回给我。它根据输入顺序返回(第一组括号外的字段,缩进)。我遇到的问题是我希望它按显示名称的字母顺序排列。因为它在主数组中它自己的数组中,所以我无法通过它重新排序完整数组。任何人都可以解决这个问题吗?谢谢。哦,它必须在 JS 中完成。

{
"0":
{"id":1,"rawId":null,"displayName":"Person 1","name":null,"nickname":null,"phoneNumbers":[{"type":"mobile","value":"phonenumb53534r","id":0,"pref":false}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":null},
"1":
{"id":2,"rawId":null,"displayName":"Person 2","name":null,"nickname":null,"phoneNumbers":[{"type":"mobile","value":"phonenumber535345","id":0,"pref":false}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":null},
"2":
{"id":3,"rawId":null,"displayName":"Person 3","name":null,"nickname":null,"phoneNumbers":[{"type":"mobile","value":"phonenumber47474","id":0,"pref":false}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":null}, goes on for a couple hundred rows

最佳答案

JavaScript 中的对象本质上不是有序的。如果你有一个数组,你可以使用它。否则,您必须自己将对象的外部部分转换为数组:

var arrayOfObj = [];

for (item in obj) {
if (obj.hasOwnProperty(item)) {
arrayOfObj.push(obj[item]);
}
}

如果你能在 之前做到这一点,你甚至可以得到 JSON,那就更好了。一旦你有了它,你就可以使用普通数组 .sort 方法

arrayOfObj.sort(function (a, b) {
if (a.displayName < b.displayName) {
return -1;
}
else if (a.displayName > b.displayName) {
return 1;
}
return 0;
});

http://jsfiddle.net/ZcM7W/

关于javascript - 按键值重新排序 Json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15047801/

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