数组转树

function toTree(arr) {
  // newArr用于存放转化成的树
  let newArr = []
  // 作为数据字典,用于方便查询找到某一项的父级项
  let map = {}

  // 制作数据字典
  arr.forEach(item => {
    // 如果当前项没有children,就添加该属性,方便转树使用
    if (!item.children) {
      item.children = []
    }
    // 把当前项的ID作为数据字典的索引,保存当前项
    map[item.id] = item
  })

  arr.forEach(item => {
    // 通过数据字典找到当前项的父级项
    let parent = map[item.pid]
    // 如果当前项有父级
    if (parent) {
      // 将当前项插入到它的父级项的children中
      // 注:由于parent的地址和arr的数据项地址相同,所以该插入操作相当于直接在arr中找到item的父级项,然后把item插入到它的父级项中
      parent.children.push('item')
    } else {
      // 如果没有父级项,则直接插入到新数组
      newArr.push(item)
    }
  })
  return newArr
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将一个 JSON 数组转换为形结构,可以使用递归的方法来构建。以下是一个示例的 JavaScript 实现: ```javascript function buildTree(jsonArray) { const map = {}; const roots = []; // 构建节点映射表 for (const item of jsonArray) { const id = item.id; const parentId = item.parentId; map[id] = { ...item, children: [] }; if (!parentId) { roots.push(map[id]); // 根节点 } else { if (!map[parentId]) { map[parentId] = { children: [] }; } map[parentId].children.push(map[id]); } } return roots; } // 示例用法: const jsonArray = [ { id: 1, name: 'Node 1', parentId: null }, { id: 2, name: 'Node 2', parentId: 1 }, { id: 3, name: 'Node 3', parentId: 1 }, { id: 4, name: 'Node 4', parentId: 2 }, { id: 5, name: 'Node 5', parentId: null }, ]; const tree = buildTree(jsonArray); console.log(tree); // 输出转换后的形结构 ``` 在这段代码中,我们定义了一个 `buildTree` 函数,它接受一个 JSON 数组作为输入,并返回转换后的形结构。 首先,我们创建一个空对象 `map` 来存储节点的映射关系,以及一个空数组 `roots` 来存储根节点。 然后,我们遍历 JSON 数组,对于每个节点,我们将其 id 作为键,将该节点的副本(包括其它属性和一个空数组 children)作为值存储在 `map` 中。 如果节点的 `parentId` 为 null,则将该节点添加到 `roots` 数组中,表示它是根节点。 如果节点的 `parentId` 不为 null,则将该节点添加到对应父节点的 `children` 数组中。 最后,我们返回 `roots` 数组,即转换后的形结构。 通过创建示例的 JSON 数组,并调用 `buildTree` 函数,我们可以将其转换为形结构并打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值