如何将后端传到前端的对象数组转化成树形结构的对象数组

具体实现原理请参考:https://blog.csdn.net/w1418899532/article/details/90065633

一、问题描述

需要被转化的对象数组:

this.state = {
test : [
                {id: 7,  name: '快鱼',  pid: 2},
                {id: 8,  name: '海澜之家',  pid: 2},
                {id: 9,  name: '森马',  pid: 2},
                {id: 13,  name: '华为mate10',  pid: 4},
                {id: 14,  name: '华为mate20',  pid: 4},
                {id: 15,  name: '华为mate30',  pid: 4},
                {id: 4,  name: '华为',  pid: 1},
                {id: 5,  name: 'ViVo',  pid: 1},
                {id: 6,  name: 'OPPO',  pid: 1},
                {id: 10,  name: '长虹',  pid: 3},
                {id: 11, name: '飞利浦',  pid: 3},
                {id: 12, name: '松下',  pid: 3},
                {id: 1,  name: '手机'},
                {id: 2,  name: '服装'},
                {id: 3,  name: '家电'}    
            ],
}

转化成树形 后的对象数组:

[
     {id: 1,  name: '手机', pid: 0, children: [
         {id: 4,  name: '华为',  pid: 1, children: [
             {id: 13,  name: '华为mate10',  pid: 4},
             {id: 14,  name: '华为mate20',  pid: 4},
             {id: 15,  name: '华为mate30',   pid: 4}
         ]},
         {id: 5,  name: 'ViVo',  pid: 1, children: []},
         {id: 6,  name: 'OPPO',  pid: 1, children: []}
     ]},
     {id: 2,  name: '服装', pid: 0, children: [
         {id: 7,  name: '快鱼',  pid: 2, children: []},
         {id: 8,  name: '海澜之家',  pid: 2, children: []},
         {id: 9,  name: '森马',  pid: 2, children: []}
     ]},
     {id: 3,  name: '家电', pid: 0, children: [
         {id: 10, name: '长虹',  pid: 3, children: []},
         {id: 11, name: '飞利浦',  pid: 3, children: []},
         {id: 12, name: '松下',  pid: 3, children: []}
     ]}    
   ]

二、解决方案

 //将json串转换成树形结构 a代表要被转换的对象数组  idStr代表数据库中的"report_config_id"  pid代表数据库中的"parent_id"
	 transData(a, idStr, pidStr, chindrenStr) {
     
		var result = [], hash = {
     }, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = a.length;
		for (; i < len; i++) {
     
			hash[a[i][id]] = a[i];
		}
		for (; j < len; j++) {
     
			var aVal = a[j], hashVP = hash[aVal[pid]];
			if (hashVP) {
     
				!hashVP[children] && (hashVP[children] = []);
				hashVP[children].push(aVal);
			} else {
     
				result.push(aVal);
			}
		}
		return result;
	}

方法的调用

 const {test} = this.state;

 // 把test对象数据转换成 树形结构
 var jsonDataTree = this.transData(test, 'id', 'pid', 'children');

你可能感兴趣的:(前端React,算法)