[英]Create nested tree Object from a flat string Array
Given the following Array of strings:给定以下字符串数组:
['A','AA','AAA','AAAA']
I am trying to convert them to an object like this using a function:我正在尝试使用 function 将它们转换为这样的 object:
{
name: 'A',
children: [
{
name: 'AA',
children: [
{
name: 'AAA',
children: [
{
name: 'AAAA'
children: []
}
]
}
]
}
]
}
I cannot find a solution that works with recursivity.我找不到适用于递归的解决方案。 Any suggestions please?
有什么建议吗?
What i've tried, and it's not working since it's lacking recursivity logic:我已经尝试过,但它没有用,因为它缺乏递归逻辑:
array = ['A','AA','AAA','AAAA']
foo(array) {
let resultArray = []
while (array.length > 0) {
const item = array.shift()
resultArray.push({
name: item,
children: array[0]
})
}
return resultArray
}
console.log(foo(array))
You can use reduceRight
:您可以使用
reduceRight
:
let result = ['A','AA','AAA','AAAA'].reduceRight( (children, name) => [{ name, children }], [] ).pop(); console.log(result);
It is a bit of an odd structure, as the children array never has more than one element in it...这是一个有点奇怪的结构,因为 children 数组中从来没有超过一个元素......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.