Js parses the multi-layer nested json, takes all the parent elements with the same elements to form a new array and returns?

such a multi-layer array,

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"
            }
        ]
    }
]

for example, the function is searchParentElementArrays;
when I pass in searchParentElementArrays (json, id), print:

[["1", "1-1", "1-1-1"],["1", "1-1", "1-1-2"],["1", "1-2"],["2-1"],["3-1","3-1-1"]]

the environmental background of the problems and what methods you have tried

related codes

/ / Please paste the code text below (do not replace the code with pictures)

what result do you expect? What is the error message actually seen?


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 standard, that's it. Otherwise, we need to judge whether key exists, whether children is an empty array, etc.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1c1e9fc-3294f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1c1e9fc-3294f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?