2015-01-07 73 views
1

我有以下輸入。從Javascript中的複雜嵌套對象值生成字符串

[{ 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'這樣的字符串是可能的。

這樣的例子的endresult應該是:

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

我現在的解決方案並沒有真正的工作.. 這是實現這一目標的最好和最高效的解決方案?提前致謝!

回答

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

+0

'嵌套可以是無止境的。所以像'test.test1.test2.test3'這樣的字符串是可能的。 ' – thefourtheye

+0

是的,只是注意到了,我認爲它只有1層深 –

+0

看起來你的工作會很好,有一個upvote –

相關問題