1

I have the following input.

    [{ name: 'modules',
       children: [ { name: 'home', children: [], allowed: true } ],
       allowed: true },

     { name: 'modules',
       children: 
         [ { name: 'new', children: [], allowed: true },
           { name: 'all', children: [], allowed: true } ],
       allowed: true },

     { name: 'groups',
       children: 
         [ { name: 'new', children: [], allowed: true },
           { name: 'all', children: [], allowed: true } ],
       allowed: true },

     { name: 'users',
       children: 
         [ { name: 'new', children: [], allowed: true },
           { name: 'all', children: [], allowed: true } ],
       allowed: true },

     { name: 'settings',
       children: 
         [ { name: 'generally', children: [], allowed: true },
           { name: 'personal', children: [], allowed: true } ],
       allowed: true }]

I would like to build string from the values like this: name.children.name.children and so on. I need every possible combination. The nesting can be endless. So a string like 'test.test1.test2.test3' is possible.

So the endresult of the example should be:

'modules.home'
'modules.new'
'modules.all'
'groups.new'
'groups.all'
'users.new'
'users.all'
'settings.generally'
'settings.personal'

My current solution does not really work.. Which is the best and most performant solution to achieve this? Thanks in advance!

2 Answers 2

3

You can use a recursive function, like this

function recursiveNamer(currentList, currentNameString, result) {

    var name = currentNameString === "" ? "" : currentNameString + ".";

    currentList.forEach(function(currentObject) {

        if (currentObject.children.length === 0) {

            result.push(name + currentObject.name);

        } else {

            recursiveNamer(currentObject.children, name + currentObject.name, result);

        }

    });

    return result;
}

console.log(recursiveNamer(inputData, "", []));

And the result would be

[ 'modules.home',
  'modules.new',
  'modules.all',
  'groups.new',
  'groups.all',
  'users.new',
  'users.all',
  'settings.generally',
  'settings.personal' ]
Sign up to request clarification or add additional context in comments.

Comments

0

You could use a loop:

for(var i=0;i<data.length;i++){
    for(var e=0;e<data[i].children.length;e++){
        console.log(data[i].name+'.'+data[i].children[e].name);
    }
}

http://jsfiddle.net/6pcjvvv0/

2 Comments

The nesting can be endless. So a string like 'test.test1.test2.test3' is possible.
Yes just noticed that, I assumed it was only 1 level deep

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.