【问题标题】:How to convert parent child array to json tree structure by javascript如何通过javascript将父子数组转换为json树结构
【发布时间】:2020-10-24 20:09:07
【问题描述】:

我有一个对象数组,希望通过 java 脚本函数将其转换为 JSON 树结构,然后在 vue js 项目中使用它。 该页面有一个需要 JSON 树结构的 vuetify 树组件。 我的数据已经存储在带有父子结构的 MySql 表中。

样品日期:

[
    {"id": 123, "parentid": 0, "name": "Mammals"},
    {"id": 456, "parentid": 123, "name": "Dogs"},
    {"id": 214, "parentid": 456, "name": "Labradors"},
    {"id": 810, "parentid": 456, "name": "Pugs"},
    {"id": 919, "parentid": 456, "name": "Terriers"}
]

结果:

[
    {
        "id": 123,
        "parentid": 0,
        "name": "Mammals",
        "children": [
            {
                "id": 456,
                "parentid": 123,
                "name": "Dogs",
                "children": [
                    {
                        "id": 214,
                        "parentid": 456,
                        "name": "Labradors"
                    },
                    {
                        "id": 810,
                        "parentid": 456,
                        "name": "Pugs"
                    },
                    {
                        "id": 919,
                        "parentid": 456,
                        "name": "Terriers"
                    }
                ]
            }
        ]
    }
]

来自该地址的样本数据:https://gist.github.com/smrchy/7040377

【问题讨论】:

    标签: javascript json tree


    【解决方案1】:

    您可以对数组执行reduce 操作,使用一个对象来存储对每个对象的引用(用于添加子对象)和一个数组来存储结果。

    const arr = [
        {"id": 123, "parentid": 0, "name": "Mammals"},
        {"id": 456, "parentid": 123, "name": "Dogs"},
        {"id": 214, "parentid": 456, "name": "Labradors"},
        {"id": 810, "parentid": 456, "name": "Pugs"},
        {"id": 919, "parentid": 456, "name": "Terriers"}
    ];
    const {res} = arr.reduce((acc,curr)=>{
      if(acc.parentMap[curr.parentid]){
        (acc.parentMap[curr.parentid].children = 
               acc.parentMap[curr.parentid].children || []).push(curr);
      } else {
        acc.res.push(curr);
      }
      acc.parentMap[curr.id] = curr;
      return acc;
    }, {parentMap: {}, res: []});
    console.log(res);

    【讨论】:

      【解决方案2】:

      @unmitigated 的响应仅在您的列表已预订时有效。

      相反,灵感来自@alexandru.pausan in Build tree array from flat array in javascript

      我觉得更容易理解:

      • 为数组中所有可能的 id 创建一个对象/字典,然后
      • 然后在将孩子与父母联系起来后查字典:
        const array = [
            { id: 919, parentid: 456, name: "Terriers" },
            { id: 456, parentid: 123, name: "Dogs" },
            { id: 214, parentid: 456, name: "Labradors" },
            { id: 810, parentid: 456, name: "Pugs" },
            { id: 123, parentid: 0, name: "Mammals" },
          ];
          
          let tree = [], arrayDictionary = {};
          
          // First map the nodes of the array to an object/dictionary where the key is their id
          array.forEach((cat) => {
            arrayDictionary[cat.id] = cat;
            arrayDictionary[cat.id]["children"] = [];
          });
          
          
          // for each entry in the dictionary
          for (var entry in arrayDictionary) {
      
            // get all the data for this entry in the dictionary
            const mappedElem = arrayDictionary[entry];
      
            // if the element has a parent, add it
            if (
              mappedElem.parentid && // the dictionary has a parent
              arrayDictionary[mappedElem["parentid"]] // and that parent exists
              ) {
      
              arrayDictionary[mappedElem["parentid"]]["children"].push(mappedElem);
            }
            // else is at the root level (parentid = null or 0)
            else {
              tree.push(mappedElem);
            }
          }
          
          console.log(tree);
      
       
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-07
        • 1970-01-01
        • 2013-03-25
        • 1970-01-01
        • 2019-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多