繁体   English   中英

如何通过javascript将父子数组转换为json树结构

[英]How to convert parent child array to json tree structure by javascript

我有一个对象数组,希望通过 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

您可以使用一个对象来存储对每个对象的引用(用于添加子对象)和一个数组来存储结果,对数组执行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);

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

相反,在从 javascript 中的平面数组构建树数组中的@alexandru.pausan 中受到了很大的启发。

我觉得更容易理解:

  • 创建数组中所有可能的 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);

 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM