JavaScript之树形结构的数据(一)

在前端JS编程中,经常需要在前端页面显示组织机构之类的树形结构数据,下面的代码可以组成一个树形结构的数据。

现成的树形结构数据如下
const Data =
[
    {
        "key": "0-0-0",
        "title": "0-0-0",
        "children": [
            {
                "key": "0-0-1",
                "title": "0-0-1",
                "children": [
                    {
                        "key": "0-0-1-1",
                        "title": "0-0-1-1"
                    },
                    {
                        "key": "0-0-1-2",
                        "title": "0-0-1-2"
                    },                    
                ]
            },
            {
                "key": "0-0-2",
                "title": "0-0-2"
            },
            {
                "key": "0-0-3",
                "title": "0-0-3"
            }
        ]
    },
    {
        "key": "0-1",
        "title": "0-1"
    }
];
const device=[
    {
        "key": 1,     
        "title": "设备1"
    },
    {
        "key": 2,
        "title": "设备2",
        children:{

      }
    },

]

const alarmInput=[
    {
        "key": 11,
        "deviceId":1,
        "title": "通道1"
    },
    {
        "key":12,
        "deviceId":1,
        "title": "通道2"
    },
    {
        "key":13,
        "deviceId":2,
        "title": "通道3"
    },     
    {
        "key":14,
        "deviceId":2,
        "title": "通道4"
    },
    {
        "key":15,
        "deviceId":2,
        "title": "通道5"
    },     

]
function tree(parent,children){
  var returnData=[];
 for(var i=0;i<parent.length;i++){
   var o={
     key:"",
     title:"",
     children:[],
   }
       o.key=parent[i].key;
       o.title=parent[i].title;
   for(var j=0;jif(parent[i].key == children[j].deviceId){
       var item= children[j];
       o.children.push(children[j]);

     }
   }//children 结束
   returnData.push(o);
 }//parent 结束
  return returnData;
}
var gData=[];
gData.push(tree(device,alarmInput));

console.log(gData);

你可能感兴趣的:(javascript)