简体   繁体   中英

Build string from complex nested object values in Javascript

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!

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' ]

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM