js把json数据转化成树形数据

/**
 * 将id、parentId这种JSON数组的数据格式转换为树节点格式
 * @param {Array} arr
 * @param {String} id
 * @param {String} pid
 * @return {Array}
 */
 function arrayToTree(arr, id, pid) {
  let data = JSON.parse(JSON.stringify(arr));
  if (!data || !data.length) return [];
  let targetData = [];                    //存储数据的容器(返回)
  let records = {};
  let itemLength = data.length;           //数据集合的个数
  for (let i = 0; i < itemLength; i++){
    let o = data[i];
    records[o[id]] = o;
  }
  for (let i = 0; i < itemLength; i++) {
    let currentData = data[i];
    let parentData = records[currentData[pid]];
    if (!parentData) {
      targetData.push(currentData);
      continue;
    }
    parentData.children = parentData.children || [];
    parentData.children.push(currentData);
  }
  return targetData;
}

/*转化函数*/

function(data, attributes) {

    let resData = data;

    let tree = [];

    for(let i = 0; i < resData.length; i++) {

        if(resData[i][attributes.parentId] === attributes.rootId) {

            let obj = {

                id: resData[i][attributes.id],

                title: resData[i][attributes.name],

                children: []

            };

            tree.push(obj);

            resData.splice(i, 1);

            i--;

        }

    }

    run(tree);

 

    function run(chiArr) {

        if(resData.length !== 0) {

            for(let i = 0; i < chiArr.length; i++) {

                for(let j = 0; j < resData.length; j++) {

                    if(chiArr[i].id == resData[j][attributes.parentId]) {

                        let obj = {

                            id: resData[j][attributes.id],

                            title: resData[j][attributes.name],

                            children: []

                        };

                        chiArr[i].children.push(obj);

                        resData.splice(j, 1);

                        j--;

                    }

                }

                run(chiArr[i].children);

            }

        }

    }

 

    return tree;

 

}

1

var data=[{id:1,parentId:0,name:"测试1"},

1

{id:2,parentId:1,name:"测试2"}]

1

2

3

4

5

<em id="__mceDel"><br>let attributes = {    //定义数据属性名称

id: 'id',

parentId: 'parentId',

name: 'groupName',<br>rootId: 0

}<br>/*调用*/<br>formatTreeData(data,attributes);<br></em>

 

 

/**
 * 将数组转换为树结构数据
 *
 * @export
 * @param {Array} array
 * @param {Object} parent 父节点
 * @param {Array} tree
 * @return {Array}
 */
function array2tree(array, parent = { id: 0 }, tree = []) {
  let treeData = tree
  const children = _.filter(array, function(child) {
    return child.parentId === parent.id
  })
  if (!_.isEmpty(children)) {
    if (parent.id === 0) {
      treeData = children
    } else {
      parent['children'] = children
    }
    _.each(children, function(child) {
      array2tree(array, child)
    })
  }

  return treeData
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JSON.stringify()方法可以将JavaScript对象转换为JSON字符串。如果要将树形结构的JSON数据展示出来,可以先将源数据进行深度克隆,然后通过遍历源数据,为每个节点添加children属性,最后使用JSON.stringify()方法将处理后的数据转换为JSON字符串。 以下是一个示例代码: ```javascript // 假设源数据为以下结构 const source = [ { id: 1, name: 'node1', parentId: null }, { id: 2, name: 'node2', parentId: 1 }, { id: 3, name: 'node3', parentId: 1 }, { id: 4, name: 'node4', parentId: 2 }, { id: 5, name: 'node5', parentId: 2 }, { id: 6, name: 'node6', parentId: 3 }, { id: 7, name: 'node7', parentId: 3 }, ]; // 对源数据进行深度克隆 const cloneData = JSON.parse(JSON.stringify(source)); // 为每个节点添加children属性 cloneData.forEach(item => { item.children = cloneData.filter(child => child.parentId === item.id); }); // 过滤出根节点 const treeData = cloneData.filter(item => item.parentId === null); // 将处理后的数据转换为JSON字符串 const jsonString = JSON.stringify(treeData); console.log(jsonString); ``` 运行以上代码,将会输出以下JSON字符串: ```json [ { "id": 1, "name": "node1", "parentId": null, "children": [ { "id": 2, "name": "node2", "parentId": 1, "children": [ { "id": 4, "name": "node4", "parentId": 2, "children": [] }, { "id": 5, "name": "node5", "parentId": 2, "children": [] } ] }, { "id": 3, "name": "node3", "parentId": 1, "children": [ { "id": 6, "name": "node6", "parentId": 3, "children": [] }, { "id": 7, "name": "node7", "parentId": 3, "children": [] } ] } ] } ] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值