在javascript中排序json对象 [英] sort json object in javascript

查看:171
本文介绍了在javascript中排序json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如有这个代码:

var json = {
    "user1" : {
        "id" : 3
    },
    "user2" : {
        "id" : 6
    },
    "user3" : {
        "id" : 1
    }
}

如何将此json排序为是这样的 -

How can I sort this json to be like this -

var json = {
    "user3" : {
        "id" : 1
    },
    "user1" : {
        "id" : 3
    },
    "user2" : {
        "id" : 6
    }
}

我使用ID对用户进行了排序..


我不知道如何在javascript中执行此操作..

I sorted the users with the IDs..
I don't know how to do this in javascript..

推荐答案

首先,这是 JSON。它是一个JavaScript对象文字。 JSON是数据的字符串表示,恰好与JavaScript语法非常相似。

First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.

其次,您有一个对象。他们没有分类。元素的顺序无法保证。如果您需要保证订单,则需要才能使用数组。这将要求您更改数据结构。

Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.

一个选项可能是使您的数据如下所示:

One option might be to make your data look like this:

var json = [{
    "name": "user1",
    "id": 3
}, {
    "name": "user2",
    "id": 6
}, {
    "name": "user3",
    "id": 1
}];

现在你有一个对象数组,我们可以对它进行排序。

Now you have an array of objects, and we can sort it.

json.sort(function(a, b){
    return a.id - b.id;
});

结果数组如下所示:

[{
    "name": "user3",
    "id" : 1
}, {
    "name": "user1",
    "id" : 3
}, {
    "name": "user2",
    "id" : 6
}];

这篇关于在javascript中排序json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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