gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:30:38 25 4
gpt4 key购买 nike

我有以下输入。

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

关于javascript - 从 Javascript 中的复杂嵌套对象值构建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27822434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com