Javascript Array in Array 转 树结构

Javascript Array in Array 转 树结构

有一组数据

[

[

path1,

path2,

file1.txt

],

[

path1,

file2.txt

],

[

file3.txt

]

]

想转成树结构

[

{

name: path1,

children: [

name: path2,

children: [

name: file1.txt

]

]

},

{

name: path1,

children: [

name: file2.txt

]

},

{

name: file3.txt

}

]

求js 写法


回答:

var list = [

[

'path1',

'path2',

'file1.txt'

],

[

'path1',

'file2.txt'

],

[

'file3.txt'

]

];

function transform(arr) {

var ret = [];

for (var i = 0; i < arr.length; ++i) {

var _arr = arr[i];

var obj = {}, _obj = obj;

for (var j = 0; j < _arr.length; ++j) {

var path = _obj.name = _arr[j];

if (path.indexOf(".") < 0) {

_obj = _obj.children = {};

}

}

ret.push(obj);

}

return ret;

}

console.dir(transform(list));


回答:

按顺序来构造树形的。

let list = [

[

'path1',

'path2',

'file1.txt'

],

[

'path1',

'file2.txt'

],

[

'file3.txt'

]

];

let arrToTree = (paths)=>Object.assign({name:paths.shift()},paths.length ?{children:[arrToTree(paths)]} : {});

list.map(paths=>arrToTree(paths));

结果

[{"name":"path1","children":[{"name":"path2","children":[{"name":"file1.txt"}]}]},{"name":"path1","children":[{"name":"file2.txt"}]},{"name":"file3.txt"}]

以上是 Javascript Array in Array 转 树结构 的全部内容, 来源链接: utcz.com/p/936154.html

回到顶部