我试着写这样的功能:
Input:
['A', '-B1', '--B2', '-C1', 'D']
Output:
{'A': {'B1': {'B2': {}}, 'C1': {}}, 'D': {}}
正如你所见,B1和C1是A的子代,B2是B1的子代.它可以在100的基础上进行任何级别的嵌套
我写了一个Javascript代码,但是当创建子元素的时候,它似乎出了问题.这是我的代码:
function fetch_levels(li, chr='-') {
var res_list = []
for (i=0; i<li.length; i++) {
item = li[i]
level = item.length - item.replace(RegExp(`^${chr}+`), '').length
key = item.replace(RegExp(`^${chr}+`), '')
value = {}
res_list.push({
level: level,
name: key,
value: value
})
}
return res_list
}
function ttree_to_json(ttree, level=0) {
result = {}
for (i = 0; i < ttree.length; i++) {
cn = ttree[i]
nn = ttree[i+1] || {'level': -1}
// Edge cases
if (cn['level'] > level) {
continue
}
if (cn['level'] < level) {
return result
}
// Recursion
if (nn['level'] == level) {
result[cn['name']] = cn['value']
} else if (nn['level'] > level) {
rr = ttree_to_json(ttree.slice(i+1), level=nn['level'])
result[cn['name']] = rr
}
else {
result[cn['name']] = cn['value']
return result
}
}
return result
}
And this is how the functions can be invoked:
console.log(ttree_to_json(fetch_levels(['A', '-B1', '--B2', '-C', 'D'])))
And the output I got is something like:
Object { B2: {…}, C: {} }
这是错误的.
Can any help me to figure out what is wrong with the JavaScript code?
该解决方案的灵感来源于here:中提到的示例代码
编辑(2022年5月11日)
我的错是我没有给出真正的问题.为了使问题更简短、更精确,我给出了不同的数据 struct .这里给出的所有答案都适用于上述DS.但我无法使我的实际DS获得所需的输出.
Here is the actual input:
[
{
"componentId": "1067256",
"componentName": "Readiness",
"shortHandName": "GTM"
},
{
"componentId": "1067343",
"componentName": "-Business Planning and Commercialization - BPC",
"shortHandName": "BPC"
},
{
"componentId": "1068213",
"componentName": "-SKU Life Cycle Management (SLM)",
"shortHandName": "SLM"
},
{
"componentId": "1068210",
"componentName": "--Partner Programs",
"shortHandName": "Partner"
},
{
"componentId": "1067317",
"componentName": "--Activation",
"shortHandName": "Activation"
},
{
"componentId": "1067346",
"componentName": "Sales Compensation",
"shortHandName": "Sales Comp"
}
]
Expected output:
{
"GTM": {
"componentId": "1067256",
"componentName": "Readiness",
"shortHandName": "GTM",
"children": {
"BPC": {
"componentId": "1067343",
"componentName": "Business Planning and Commercialization - BPC",
"shortHandName": "BPC",
"children": {
"Partner": {
"componentId": "1068210",
"componentName": "Partner Programs",
"shortHandName": "Partner",
"children": {}
},
"Activation": {
"componentId": "1067317",
"componentName": "Activation",
"shortHandName": "Activation",
"children": {}
}
}
},
"SLM": {
"componentId": "1068213",
"componentName": "SKU Life Cycle Management (SLM)",
"shortHandName": "SLM",
"children": {}
}
}
},
"Sales Comp": {
"componentId": "1067346",
"componentName": "Sales Compensation",
"shortHandName": "Sales Comp",
"children": {}
}
}
Explanation:
- 使用componentName,父级和子级关系(或级别)基于
-
决定,-
可以是任何嵌套级别. -
shortHandName
用作键,作为对象的值应包含所有属性,包括新添加的属性children
-
children
将具有相同的 struct ,最低级别的子元素将具有{}
.
对我来说,很难理解所有的答案,所以我可以让它们适用于我提到的新DS.