简体   繁体   English

如何在jQuery中对JSON对象进行排序

[英]How to sort json object in jquery

I have a JSON object like: 我有一个JSON对象,例如:

{
    "resp" : [
        {
            "name" : "s"
        }, 
        {
            "name" : "c"
        }, 
        {
            "name" : "f"
        }
    ]
}

Here, I want to sort the object by name values in alphabetical order. 在这里,我想按name值按字母顺序对对象进行排序。
So, it should become this object: 因此,它应成为此对象:

{
    "resp" : [
        {
            "name" : "c"
        }, 
        {
            "name" : "f"
        },
        {
            "name" : "s"
        }
    ]
}

How how can I implement it? 我该如何实施?

You should sort the array inside the JavaScript object prior to the JSON serialization. 您应该在JSON序列化之前对JavaScript对象中的数组进行排序。 A serialized JavaScript object is nothing more than a string and therefore shouldn't be sorted. 序列化的JavaScript对象不过是一个字符串,因此不应进行排序。 Take a look at this: 看看这个:

var obj = {
    rest: [
        { name: "s" },
        { name: "c" },
        { name: "f" }
    ]
};

function compare(a, b) {
    if (a.name< b.name)
        return -1;
    if (a.name > b.name)
        return 1;
    return 0;
}

obj.rest.sort(compare);

JSON.stringify(obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM