-2

I have an object that contains the following data. How can I get all the data in the title key using the recursive function? I want a function return a array include a, b, c, d, e, f

{
                children: [
                    {
                        children: [
                            {
                                children: [],
                                title: "a"
                            }
                        ],
                        title: "b"
                    },
                    {
                        children: [
                            {
                                children: [],
                                title: "c"
                            },
                            {
                                children: [],
                                title: "d"
                            }
                        ],
                        title: "e"
                    }
                ],
                title: "f"
            }
Edris Ahani
  • 1
  • 1
  • 2
  • Have you tried anything? Just seeing a data structure and zero code attempt? (A data structure even in the language you chose to tag is *not* a code attempt by itself.) – mardubbles Apr 16 '22 at 09:13

2 Answers2

0

You can do something like this:

function drill(t, n) { 
    if (n.length > 0) { 
        for (let elem of n) { 
            t.push(elem.title); 
            drill(t, elem.children) 
        } 
    } 
    return t 
}

As @rickhg12hs did here

nimrod serok
  • 14,151
  • 2
  • 11
  • 33
0

Following a solution using modern syntax. extractTitles recursively produces arrays of titles as long as there are children and reduces them to a single array.

const extractTitles = (arr) =>
  arr.reduce((prev, { children, title }) => [...prev, title, ...(children.length ? extractTitles(children) : [])], []);

extractTitles(tree);

Or you can use flatmap.

const extractTitles = ({ title, children = [] }) =>
  [title, ...children.flatMap(extractTitles)];

extractTitles(tree);
// ["f","b","a","e","c","d"]
Mulan
  • 129,518
  • 31
  • 228
  • 259
alexanderdavide
  • 1,487
  • 3
  • 14
  • 22