You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JS对多层嵌套JSON的每一层按name字段排序

实现方案

核心思路是用递归遍历整个嵌套结构,每一层遇到children数组就按name字段的字典序排序,再递归处理每个子节点即可。

具体代码实现

// 递归排序函数
function sortTreeNodeByName(node) {
  // 仅当存在有效children数组时执行排序逻辑
  if (Array.isArray(node.children)) {
    // 按name字段的字典序升序排序,天然支持中英文的自然排序规则
    node.children.sort((a, b) => a.name.localeCompare(b.name))
    // 递归处理每个子节点的下层结构
    node.children.forEach(child => sortTreeNodeByName(child))
  }
  return node
}

// 测试用例:你的原始JSON数据
const originalData = {
  "name":"Scorpiones",
  "children":[
    {
      "name":"Parabuthus",
      "children":[
        {
          "name":"Parabuthus schlechteri"
        },
        {
          "name":"Parabuthus granulatus"
        }
      ]
    },
    {
      "name":"Buthidae",
      "children":[
        {
          "name":"Androctonus",
          "children":[
            {
              "name":"Androctonus crassicauda"
            },
            {
              "name":"Androctonus bicolor"
            }
          ]
        }
      ]
    }
  ]
}

// 调用排序得到结果
const sortedData = sortTreeNodeByName(originalData)
console.log(JSON.stringify(sortedData, null, 2))

排序效果说明

处理后每一层节点都会按name升序排列:

  • 根节点的children中Buthidae会排在Parabuthus前面
  • Parabuthus的children中Parabuthus granulatus排在Parabuthus schlechteri前面
  • Androctonus的children中Androctonus bicolor排在Androctonus crassicauda前面

如果需要改为降序排序,仅需要把sort回调的返回值修改为b.name.localeCompare(a.name)即可。

内容的提问来源于stack exchange,提问作者Gorkov Aleksey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:36:02