js解析多层嵌套的json,取出所有父元素相同元素组成新数组并返回?

比如这样的一个多层数组,

let json = [
    {
        id: '1',
        name: '节点1',
        children: [
            {
                id: '1-1',
                name: '节点1-1',
                children: [
                    {
                        id: '1-1-1',
                        name: '节点1-1-1'
                    },
                    {
                        id: '1-1-2',
                        name: '节点1-1-2'
                    }
                ]
            },
            {
                id: '1-2',
                name: '节点1-2'
            }
        ]
    },
    {
        id: '2-1',
        name: '节点2-1'
    },
    {
        id: '3-1',
        name: '节点3-1',
        children: [
            {
                id: '3-1-1',
                name: '节点3-1-1'
            }
        ]
    }
]

比如说函数为searchParentElementArrays;
当我传入searchParentElementArrays(json, id)的时候打印:

[['1', '1-1', '1-1-1'],['1', '1-1', '1-1-2'],['1', '1-2'],['2-1'],['3-1','3-1-1']]

问题出现的环境背景及自己尝试过哪些方法

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

你期待的结果是什么?实际看到的错误信息又是什么?

阅读 3.5k
1 个回答
function searchParentElementArrays (json, key) {
  const res = []
  const f = (json, arr) => json.forEach(val => val.children ? f(val.children, [...arr, val[key]]) : res.push([...arr, val[key]]))
  f(json, [])
  return res
}

console.log(searchParentElementArrays(json, 'id'))

json标准的话就这样 不然还需判断key是否存在 children是否是空数组之类的

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