0%

JS 数组字符串转换为对象

用 glob 拿到了文件列表,想转换成 tree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 转换前:
let list = [
'src/index.js',
'src/aaa/1.js',
'src/aaa/index.js',
'src/aaa/bbb/2.js',
'src/aaa/bbb/3.js',
'src/aaa/bbb/4.js',
];

// 转换后
let out = {
src: {
'index.js': 'index.js',
aaa: {
'1.js': '1.js',
'index.js': 'index.js',
bbb: {
'2.js': '2.js',
'3.js': '3.js',
'4.js': '4.js',
},
},
},
};

暂时没想到更优雅的方式,傻傻的循环递归把

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let list = e.split('\r\n');

let obj = {};
for (let index = 0; index < list.length; index++) {
const element = list[index];
let arr = element.split('/');
let temp = obj;
for (let index = 0; index < arr.length; index++) {
const str = arr[index];
if (index + 1 === arr.length) {
temp[str] = str;
} else {
if (!temp[str]) {
temp[str] = {};
}
temp = temp[str];
}
}
}
console.log(`obj`, obj);

类似的场景

JS Tree 树状数据 Object Array互转