[FIXED] Get all paths to custom JSON object

Issue

I need help to come up with a solution to retrieve all possible paths to an array containing several JSON objects containing the two keys: name[String] and children [Array].
For any given JSON input, I need an array of strings with all routes in the JSON, returning only the name of each item. The input array object can contain any number of nested children.

For example:

Obj = [
 { name: ‘name1’ },
 { name: ‘name2’ },
 { name: ‘name3’, children:[
   { name: name3Child1 },
   { name: name3Child2 },
   { name: name3Child3, children:[{ name: 'name3Child3Child1' }] }
  ]
 },
 { name: ‘name4’ },
]

With the above example, the output I’ll need is:

result = [
 'name1',
 'name2',
 'name3',
 'name3.name3Child1',
 'name3.name3Child2',
 'name3.name3Child3.name3Child3Child1',
 'name4',
]

If you can provide ES6+ examples, I’d really appreciate it. I’ve searched online but many examples relate to standard JSON objects, where as this is in a custom format.

Thanks

Solution

const obj = [
    { name: 'name1' },
    { name: 'name2' },
    {
        name: 'name3',
        children: [
            { name: 'name3Child1' },
            { name: 'name3Child2' },
            { name: 'name3Child3', children: [{ name: 'name3Child3Child1' }] },
        ],
    },
    { name: 'name4' },
]

const Recursive = (data, prefix = []) =>
    data.reduce((acc, val) => {
        acc.push(
            `${prefix.join('.')}${prefix.length > 0 ? '.' : ''}${val.name}`
        )

        if (val.children?.length > 0)
            acc.push(...Recursive(val.children, [...prefix, val.name]))

        return acc
    }, [])

console.log(Recursive(obj))

Answered By – kennarddh

Answer Checked By – Marie Seifert (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published