从 Javascript 中的复杂嵌套对象值构建字符串
Build string from complex nested object values in 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'这样的字符串是可能的。
所以这个例子的最终结果应该是:
'modules.home'
'modules.new'
'modules.all'
'groups.new'
'groups.all'
'users.new'
'users.all'
'settings.generally'
'settings.personal'
我当前的解决方案实际上不起作用。实现此目的的最佳和性能最高的解决方案是什么?提前感谢!
你可以使用递归函数,像这样
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' ]
你可以使用循环:
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/
相关文章:
- 用javascript从列表对象(JSON的)构建diffrent选项卡
- 正在寻找从JSON/对象构建DOM客户端的JS库
- 从Javascript动态构建JSON对象列表
- 返回它在Javascript中构建的新对象
- 通过推送json构建一个数组对象
- d3.js力布局图:如何从头开始构建nodes对象
- 使用javascript在for循环中构建对象
- 如何使用rails 3.1.4中的FormBuilder.new构建表单生成器对象
- 如何迭代对象/数组中的项,并构建嵌套的JSON
- 循环遍历JQueryUI选项卡控件中的每个选项卡,并构建一个对象数组
- 如何从 jQuery 对象构建 jQuery 对象
- jQuery - 基于作为函数参数传递的对象构建动态 if 语句
- 如何使用嵌套的 JSON 对象构建 JSON 对象
- 提交时的对象构建会导致应用程序堵塞
- JavaScript日期对象构建错误的日期
- 将onclick事件的参数传递到使用数据对象构建HTML的函数中——到目前为止在js中只完成了一半
- 通过ID参数参照另一个对象构建数组
- 如何基于这个简单对象构建这个复杂的数组
- 如何从对象构建查询字符串
- jQuery选择器和对象构建