[英]JavaScript: Converting a flat array into a tree like structure without using `eval`
I have an array like this ["aaa","aaa","bbb","ccc"]
. 我有一个像这样的数组["aaa","aaa","bbb","ccc"]
。
what I need is convert it into a form like this: 我需要的是将其转换成这样的形式:
{ "aaa" :
{ "aaa" :
{ "bbb" :
{ "ccc" : 1 }
}
}
}
I know eval
can do the trick, however is there any prettier solution? 我知道eval
可以解决问题,但是有没有更漂亮的解决方案?
Thank you for reading my post. 感谢您阅读我的帖子。
Use Array.reduceRight()
. 使用Array.reduceRight()
。 On each iteration return an object, with the previous result as the value of the current property: 在每次迭代中,返回一个对象,其前一个结果为当前属性的值:
const arr = ["aaa","aaa","bbb","ccc"] const result = arr.reduceRight((r, s) => ({ [s]: r }), 1) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.