通过键值对Json数组重新排序 [英] Re-order Json array by key value

查看:444
本文介绍了通过键值对Json数组重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的格式返回给我的联系人列表.它根据输入顺序返回(第一组括号外的字段,缩进).我遇到的问题是我希望它按displayName的字母顺序排序.因为那是在主数组中的它自己的数组中,所以我很难让整个数组由它重新排序.有人能弄清楚吗?谢谢.哦,这必须用JS完成.

I have a contact list that is returned to me in this very long form. It is getting returned Based on order of entry (the field outside the first set of brackets, indented). The problem I'm having is I want it to order alphabetically by displayName. Since that is in it's own array inside of the main one I'm having trouble getting the full array to reorder by it. Can anyone figure this out? Thanks. Oh and it's got to be done in 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中的对象本质上不是顺序的.如果您有一个数组,则可以使用它.否则,您必须自己将对象的外部部分转换为数组:

Objects in JavaScript are not ordinal by nature. If you have an array, you can work with that. Otherwise, you have to convert the outer part of the object into an array yourself:

var arrayOfObj = [];

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

如果您可以在之前做到这一点,那么您甚至可以获得JSON,那就更好了.一旦有了,就可以使用常规数组.sort方法

If you can do that before you even get the JSON, so much the better. Once you have that, you can just use the normal array .sort method

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/

这篇关于通过键值对Json数组重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆