在Javascript中从复杂的嵌套对象值构建字符串

时间:2015-01-07 15:12:19

标签: javascript recursion

我有以下输入。

    [{ 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 }]

我想从像这样的值构建字符串:name.children.name.children等等。我需要一切可能的组合。筑巢可以是无穷无尽的。所以像'test.test1.test2.test3'这样的字符串是可能的。

所以示例的结果应该是:

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

我目前的解决方案并不真正有效.. 哪个是实现这一目标的最佳和最高效的解决方案?提前致谢!

2 个答案:

答案 0 :(得分:3)

您可以使用递归函数,例如

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, "", []));

结果将是

[ 'modules.home',
  'modules.new',
  'modules.all',
  'groups.new',
  'groups.all',
  'users.new',
  'users.all',
  'settings.generally',
  'settings.personal' ]

答案 1 :(得分:0)

您可以使用循环:

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/