在没有任何父信息的情况下将展平数组转换为父子数组
Convert Flatten Array to Parent Child Array Without any Parent Information
我在将展平数组转换为树 node/parent 子格式数组时遇到问题,我曾考虑使用递归解决方案,但我仍然不知道如何实现它。最好的方法可能是对列表进行分组,它是对象项中唯一的操作字符串代码。就像 01.05 || 01.05.011 || 01.05.011.0001|| 01.05.011.0002|| 01.05.011.0003
我的目标只是想将那些代码转换成这样:
{
code: 01,
child: [
code : 05,
child: [{
code: 011,
child: [
{
code: 0001,
child:[]
},
{
code: 0002,
child:[]
},
{
code: 0003,
child:[]
}
]
}]
]
}
如何解决这个问题?
您可以将字符串按点拆分,并将每个部分作为嵌套结构的新级别。
var array = ['01.05', '01.05.011', '01.05.011.0001', '01.05.011.0002', '01.05.011.0003'],
result = array.reduce((r, s) => {
s
.split('.')
.reduce((children, code) => {
var temp = children.find(o => o.code === code);
if (!temp) children.push(temp = { code, children: [] });
return temp.children;
}, r);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
我在将展平数组转换为树 node/parent 子格式数组时遇到问题,我曾考虑使用递归解决方案,但我仍然不知道如何实现它。最好的方法可能是对列表进行分组,它是对象项中唯一的操作字符串代码。就像 01.05 || 01.05.011 || 01.05.011.0001|| 01.05.011.0002|| 01.05.011.0003
我的目标只是想将那些代码转换成这样:
{
code: 01,
child: [
code : 05,
child: [{
code: 011,
child: [
{
code: 0001,
child:[]
},
{
code: 0002,
child:[]
},
{
code: 0003,
child:[]
}
]
}]
]
}
如何解决这个问题?
您可以将字符串按点拆分,并将每个部分作为嵌套结构的新级别。
var array = ['01.05', '01.05.011', '01.05.011.0001', '01.05.011.0002', '01.05.011.0003'],
result = array.reduce((r, s) => {
s
.split('.')
.reduce((children, code) => {
var temp = children.find(o => o.code === code);
if (!temp) children.push(temp = { code, children: [] });
return temp.children;
}, r);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }