gpt4 book ai didi

javascript - 如何从具有组的用户列表中创建具有地址字符串的组?

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:33 25 4
gpt4 key购买 nike

我需要从用户列表中获取唯一组的列表,其中每个用户都具有不同级别的一个或多个组的成员资格。这些级别形成了一个层次结构,我希望将其作为地址(类似于 IP 地址)保存在组中。用户必须属于层次结构中的所有组,因此,例如,如果不是上述所有组的成员,就不可能成为 3 级组的成员。我从我无法控制的 API 获取用户列表,因此遗憾的是传入结构无法更改。

给出以下示例用户列表:

const users = [
{
'Level 1': 'first',
'Level 2': 'second',
'Level 3': 'third'
},
{
'Level 1': 'first',
'Level 2': 'second',
'Level 3': 'another'
}
]

当调用如下函数时:const groups = getGroups(users})它应该返回:

const expectedGroups = [
{
name: 'first',
address: '1'
},
{
name: 'second',
address: '1.1'
},
{
name: 'third',
address: '1.1.1'
},
{
name: 'another',
address: '1.1.2'
}
]

最佳答案

您可以按顺序获取对象的值,将对象作为所见名称的引用,并为新名称添加一个包含所有级别信息的新对象。

function getGroups(array) {
var result = [],
object,
levels = { max: 0, value: '' },
i, name, level, key;

for (object of array) {
i = 1;
key = `Level ${i}`;
level = levels;

while (key in object) {
name = object[key];
if (!level[name]) {
level[name] = { value: (level.value + (level.value && '.') || '') + ++level.max, max: 0 };
result.push({ name, address: level[name].value });
}
level = level[name];
key = `Level ${++i}`;
}
}
return result;
}


var users = [{ 'Level 1': 'first', 'Level 2': 'second', 'Level 3': 'third' }, { 'Level 1': 'first', 'Level 2': 'second', 'Level 3': 'another' }],
groups = getGroups(users);

console.log(groups);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何从具有组的用户列表中创建具有地址字符串的组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59663902/

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