gpt4 book ai didi

javascript - 转换具有父子关系的逗号分隔字符串

转载 作者:行者123 更新时间:2023-12-03 06:30:18 24 4
gpt4 key购买 nike

如何使用 Javascript 根据 ; 分隔值转换以下具有父子关系的数组。有什么快速的方法吗?

var arr = [
'Dept;Accounting',
'Dept;ATG;Business',
'Dept;Cloud Services',
'Dept;Consulting',
'Dept;Education',
'Dept;Finance',
'Dept;Hardware',
'Dept;HR',
'Dept;Industries',
'Dept;ATG',
'Dept;ADIU',
'Dept;Legal',
'Dept;Marketing',
'Dept;Office',
'Dept;Products',
'Dept;Project Managing',
'Dept;Products Marketing'
]

预期输出应该是

var finalarr = [{
'Title': 'Dept', 'Childs': [
{ 'Title': 'Accounting' },
{
'Title': 'ATG', 'Childs': [
{
'Title': 'Business'
}
]
},
...
]}];

就像创建 TreeView 类型导航一样

最佳答案

我建议使用代码来生成这种简洁的树结构:

{
"Dept": {
"Accounting": {},
"ATG": {
"Business": {}
},
"Cloud Services": {},
"Consulting": {},
"Education": {},
"Finance": {},
"Hardware": {},
"HR": {},
"Industries": {},
"ADIU": {},
"Legal": {},
"Marketing": {},
"Office": {},
"Products": {},
"Project Managing": {},
"Products Marketing": {}
}
}

如果您特别需要子数组类型的结构,那么您可以使用我在下面的代码中提供的第二个函数,它将输出转换为该结构。

检查以下 ES6 代码片段的输出:

function buildTree(arr) {
return arr.reduce((tree, csv) => {
csv.split(';').reduce((obj, title) => obj[title] = obj[title] || {}, tree);
return tree;
}, {});
}

function convertTree(tree) {
return Object.keys(tree).map(title => {
var obj = { title: title };
var children = convertTree(tree[title]);
if (children.length) obj.children = children;
return obj;
});
}

// Sample data
var arr = [
'Dept;Accounting',
'Dept;ATG;Business',
'Dept;Cloud Services',
'Dept;Consulting',
'Dept;Education',
'Dept;Finance',
'Dept;Hardware',
'Dept;HR',
'Dept;Industries',
'Dept;ATG',
'Dept;ADIU',
'Dept;Legal',
'Dept;Marketing',
'Dept;Office',
'Dept;Products',
'Dept;Project Managing',
'Dept;Products Marketing'
];

// Convert to key-based nested structure
var tree = buildTree(arr);
//console.log(tree);

// Convert to children-array-based nested structure
var tree2 = convertTree(tree) ;
console.log(tree2);

关于javascript - 转换具有父子关系的逗号分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38479174/

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