最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to sort json object in jquery - Stack Overflow

programmeradmin5浏览0评论

I have a JSON object like:

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

Here, I want to sort the object by name values in alphabetical order.
So, it should bee this object:

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

How how can I implement it?

I have a JSON object like:

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

Here, I want to sort the object by name values in alphabetical order.
So, it should bee this object:

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

How how can I implement it?

Share Improve this question edited Jun 17, 2015 at 8:02 Yeldar Kurmangaliyev 34.3k13 gold badges64 silver badges104 bronze badges asked Jun 15, 2015 at 7:01 DeenDeen 6212 gold badges16 silver badges30 bronze badges 2
  • stackoverflow./questions/881510/sorting-json-by-values – Alex Coloma Commented Jun 15, 2015 at 7:10
  • Hello! I have edited your code styling, added some explanations and relevant tags. Please, review the changes. – Yeldar Kurmangaliyev Commented Jun 17, 2015 at 8:02
Add a ment  | 

1 Answer 1

Reset to default 6

You should sort the array inside the JavaScript object prior to the JSON serialization. A serialized JavaScript object is nothing more than a string and therefore shouldn't be sorted. Take a look at this:

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

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

obj.rest.sort(pare);

JSON.stringify(obj)
发布评论

评论列表(0)

  1. 暂无评论