javascript - 按值对 JSON 进行排序

标签 javascript php jquery json sorting

<分区>

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

这是我的 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"
}]

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

最佳答案

我建议使用 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>');

关于javascript - 按值对 JSON 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35576041/

相关文章:

php - 在方法中声明 protected 变量

php - 在没有额外标记的情况下,在 SQL 中保留回车以供 HTML 显示?

javascript - 如何为谷歌地图信息窗口设置边界半径

javascript - 隐藏播放器的 div 时停止 JWPlayer

javascript - 为什么将数据加载到 Meteor Collection 中需要这么长时间?

javascript - 避免警告 "Use of this in closure"

javascript - jQuery.submit() 是否缩小了 DOM 元素的范围?

javascript - helpers {{#if }} 不使用expressjs 和express3-handlebars 进行渲染

php - tools/android 返回找不到 sdkmanager.jar

jquery - 创建 AJAX 丰富的移动网站?