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;j<children.length;j++){
     if(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);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值