在javascript中对json对象进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17684921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:58:11  来源:igfitidea点击:

sort json object in javascript

javascriptjsonsorting

提问by julian

For example with have this code:

例如有这个代码:

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

How can I sort this json to be like this -

我怎样才能把这个 json 排序成这样 -

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

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

我用 ID 对用户进行了排序..
我不知道如何在 javascript 中做到这一点..

回答by Rocket Hazmat

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

首先,这不是JSON。它是一个 JavaScript 对象字面量。JSON 是数据的字符串表示,恰好非常类似于 JavaScript 语法。

Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you needto 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;
});

The resulting array will look like:

结果数组将如下所示:

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

回答by Vyacheslav Cotruta

Here is a simple snippet that sorts a javascript representation of a Json.

这是一个简单的片段,用于对 Json 的 javascript 表示进行排序。

function isObject(v) {
    return '[object Object]' === Object.prototype.toString.call(v);
};

JSON.sort = function(o) {
if (Array.isArray(o)) {
        return o.sort().map(JSON.sort);
    } else if (isObject(o)) {
        return Object
            .keys(o)
        .sort()
            .reduce(function(a, k) {
                a[k] = JSON.sort(o[k]);

                return a;
            }, {});
    }

    return o;
}

It can be used as follows:

它可以按如下方式使用:

JSON.sort({
    c: {
        c3: null,
        c1: undefined,
        c2: [3, 2, 1, 0],
    },
    a: 0,
    b: 'Fun'
});

That will output:

这将输出:

{
  a: 0,
  b: 'Fun',
  c: {
    c2: [3, 2, 1, 0],
    c3: null
  }
}

回答by Katana314

In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to displaythe sorted values in some way? As Bergi said in the comments, you can never quite relyon Javascript objects ( {i_am: "an_object"}) to show their properties in any particular order.

在某些方面,您的问题似乎非常合理,但我仍然可能将其标记为XY problem. 我猜最终结果是您想以某种方式显示排序后的值?正如 Bergi 在评论中所说,您永远不能完全依赖Javascript 对象 ( {i_am: "an_object"}) 以任何特定顺序显示其属性。

For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:

对于显示顺序,我可能建议您获取对象的每个键(即i_am)并将它们排序为有序数组。然后,在检索要显示的对象元素时使用该数组。伪代码:

var keys = [...]
var sortedKeys = [...]
for (var i = 0; i < sortedKeys.length; i++) {
  var key = sortedKeys[i];
  addObjectToTable(json[key]);
}

回答by user4081130

if(JSON.stringify(Object.keys(pcOrGroup).sort()) === JSON.stringify(Object.keys(orGroup)).sort())
{
    return true;
}