请教一个js数据格式化问题

现有数据:原数组

const arr = [
    {
        id: 1,
        children: [
            {id: 2},
            {id: 3}
        ]
    },
    {
        id: 4,
        children: [
            {
                id: 5,
                chidldren: [
                    {id: 6},
                    {id: 7}
                ]
            }
        ]
    },
    ...
];

索引数据

const arrIndex = [1,2,3,4,5,6,7]

目标数据 有什么好的方法?

const arrTarget = [
    [1, 2],
    [1, 3],
    [4, 5, 6],
    [4, 5, 7],
];

写代码些懵逼了 😭
也不是拿来注意,给个思路也可以的。

阅读 3k
4 个回答

原始回答

function deep(arr, pre){
    pre = pre || []
    let res = []
    arr.forEach(item => {
        let target = pre.concat([item.id])
        if(item.children && item.children.length){
            target = deep(item.children, target)
            res = res.concat(target)
        }else{
            res.push(target)
        }
    })
    
    return res
}

const arrTarget = deep(arr)

增加逻辑

function deep(arr, pre){
    pre = pre || []
    let res = []
    arr.forEach(item => {
        // 只有在索引数组中出现过的才会被保留
        let target = arrIndex.includes(item.id) ? pre.concat([item.id]) : []
        if(item.children && item.children.length){
            target = deep(item.children, target)
            res = res.concat(target)
        }else{
            // target为空时不用push
            target.length && res.push(target)
        }
    })
    return res
}

一维的children二维的chidldren,确定名称是不一致的吗?如果一致,二维名称你应该多打了一个d

新手上路,请多包涵

要用递归遍历

function getData(data){
    var root = {
        id: 'root',
        children: data
    }
    const result = []
    const list = [{ node: root, path: [] }] 
    while (list.length) {
      const { node, path } = list.shift()
      console.log(node)
      if(!node.children || !node.children.length){
        result.push(path)
      }
      if(node.children && node.children.length){
          node.children.filter(c => c && list.push({ node: c, path: [...path, c.id] }))
      }
    }
    console.log(result)
    return result
}

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题