如何数组转换为树? [英] How to convert array to tree?
本文介绍了如何数组转换为树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数组
[A,B,C]
[一,B,D]
我想它转换成
{
A :
{
乙:
{
C:空,
D:空
}
}
}
我怎么能这样做?
解决方案
VAR树= {}功能addToTree(树阵){
对于(VAR I = 0,长度= array.length; I<长度;我++){
树树= [阵列[我] =树[阵列[我]] || {}
}
}addToTree(树,[一,B,C])
addToTree(树,[一,B,D])/ * {
一个: {
B:{
C: {},
D:{}
}
}
} * /
唯一不会做的是设置树空的树叶 - 这其中设置为一个空的对象。可以吗?
如果你想要的叶子为空,然后用下面的代替:
函数addToTree(树阵){
对于(VAR I = 0,长度= array.length; I<长度;我++){
树树= [阵列[我] =((我==长度 - 1)空:树[阵列[我]] || {})
}
}//或者,如果没有我长== - 1支票在每个迭代:
功能addToTree(树阵){
对于(VAR I = 0,长度= array.length; I<长度-1;我++){
树树= [阵列[我] =树[阵列[我]] || {};
}
树[阵列[我] = NULL;
}/ * {
一个: {
B:{
C:空,
D:空
}
}
} * /
I have two arrays
["a", "b", "c"]
["a", "b", "d"]
I want to convert it to
{
a :
{
b :
{
c : null,
d : null
}
}
}
How can I do that?
解决方案
var tree = {}
function addToTree(tree, array) {
for (var i = 0, length = array.length; i < length; i++) {
tree = tree[array[i]] = tree[array[i]] || {}
}
}
addToTree(tree, ["a", "b", "c"])
addToTree(tree, ["a", "b", "d"])
/*{
"a": {
"b": {
"c": {},
"d": {}
}
}
}*/
Only thing it doesn't do is set the leaves of the tree to null -- it sets them to an empty object. Is that ok?
If you want the leaves to be null, then use the following instead:
function addToTree(tree, array) {
for (var i = 0, length = array.length; i < length; i++) {
tree = tree[array[i]] = ((i == length - 1) ? null : tree[array[i]] || {})
}
}
// or, without the i == length - 1 check in each iteration:
function addToTree(tree, array) {
for (var i = 0, length = array.length; i < length -1; i++) {
tree = tree[array[i]] = tree[array[i]] || {};
}
tree[array[i]] = null;
}
/*{
"a": {
"b": {
"c": null,
"d": null
}
}
}*/
这篇关于如何数组转换为树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文