Skip to content

JS 数组字符串转换为对象

Published: at 02:34 PMSuggest Changes

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

// 转换前:
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',
      },
    },
  },
};

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

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);

类似的场景

{% post_link js-tree-array-to-object JS Tree 树状数据 Object Array 互转 %}


Previous Post
HTML 回车换行与 CSS
Next Post
JavaScript 数组分片切割方法