List(数组)转Json_js版_Java版_v1.0.0

代码

Js版

  • 先看看效果:
    在这里插入图片描述
list数据
const list = [
      {"id":"1","parentId":"0","name":"逍遥子","value": + `9101212` },
      {"id":"2","parentId":"1","name":"无崖子","value": + `9101212` },
      {"id":"3","parentId":"1","name":"天山童姥","value": + `9101212` },
      {"id":"4","parentId":"1","name":"李秋水","value": + `9101212` },
      {"id":"5","parentId":"1","name":"小师妹","value": + `9101212` },
      {"id":"6","parentId":"2","name":"虚竹","value": + `9101212` },
      {"id":"7","parentId":"2","name":"丁春秋","value": + `9101212` },
      {"id":"8","parentId":"3","name":"虚竹-黑化","value": + `9101212` },
      {"id":"9","parentId":"4","name":"梦姑","value": + `9101212` },
      {"id":"10","parentId":"5","name":"王夫人","value": + `9101212` },
      {"id":"11","parentId":"10","name":"王语嫣","value": + `9101212` },
      {"id":"12","parentId":"7","name":"摘星子","value": + `9101212` },
      {"id":"13","parentId":"7","name":"阿紫","value": + `9101212` },
      {"id":"14","parentId":"2","name":"苏星河","value": + `9101212` },
      {"id":"15","parentId":"14","name":"函谷八友","value": + `9101212` },
      {"id":"16","parentId":"14","name":"无名氏","value": + `9101212` },
    ]
递归 也就是说向子节点(子孩子)写入key,子孩子的name作为key
const getJsonTree = function(data, parentId) {

        let itemArr = {};
        for (let i = 0; i < data.length; i++) {

          const node = data[i];

          const nodeName = node.name

          if (node.parentId === parentId) { // 是这个节点的子孩子

            let child = getJsonTree(data, node.id)

            itemArr[nodeName] = child;

            // console.log(`JSON化child === `, JSON.stringify(child))
            if (JSON.stringify(child) === `{}`) {
              // console.log(`空json`, node.value, itemArr)
              itemArr[nodeName] = node.value
            }

          }
        }

        return itemArr
      }
执行 由list生成级联Json
console.log(JSON.stringify(getJsonTree(list,'0')))
效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值