Javascript 按值对 JSON 进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35576041/
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-08-23 17:54:40  来源:igfitidea点击:

Sort JSON by value

javascriptphpjqueryjsonsorting

提问by diank

how I can sort my json file by name -> value? I want to show by asc value of tag name. Any idea how to convert my json file?

如何按名称-> 值对我的 json 文件进行排序?我想按标签名称的 asc 值显示。知道如何转换我的 json 文件吗?

Here is how look my JSON file:

这是我的 JSON 文件的外观:

[{
    "id": "105",
    "name": "FIAT",
    "active": true,
    "parentId": "1"
}, {
    "id": "106",
    "name": "AUDI",
    "active": true,
    "parentId": "1"
}, {
    "id": "107",
    "name": "BMW",
    "active": true,
    "parentId": "1"
}, {
    "id": "109",
    "name": "RENAULT",
    "active": true,
    "parentId": "1"
}]

I will be grateful if someone help me. Thanks in advance.

如果有人帮助我,我将不胜感激。提前致谢。

回答by Nina Scholz

I suggest to use Array#sort()

我建议使用 Array#sort()

var data = [{ "id": "105", "name": "FIAT", "active": true, "parentId": "1" }, { "id": "106", "name": "AUDI", "active": true, "parentId": "1" }, { "id": "107", "name": "BMW", "active": true, "parentId": "1" }, { "id": "109", "name": "RENAULT", "active": true, "parentId": "1" }];
data.sort(function (a, b) {
    return a.name.localeCompare(b.name);
});
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');

回答by dorado

Pretty straight-forward.

很直接。

data = [{
    "id": "105",
    "name": "FIAT",
    "active": true,
    "parentId": "1"
}, {
    "id": "106",
    "name": "AUDI",
    "active": true,
    "parentId": "1"
}, {
    "id": "107",
    "name": "BMW",
    "active": true,
    "parentId": "1"
}, {
    "id": "109",
    "name": "RENAULT",
    "active": true,
    "parentId": "1"
}];


data.sort(function(a, b) {
    return a.name > b.name;
});

console.log(data);