把 文件夹下有多个子文件夹并且数量不定, **层级不定**转化为对象的形式

路径

├── module-a
│ ├── function-a
│ │ ├── index.js
│ │ ├── sub-function-a
│ │ │ ├── grand-func.js
│ │ │ └── index.js
│ │ └── sub-function-b.js
│ ├── function-b.js
│ ├── index
│ │ ├── index.js
│ │ └── sub-function-c.js
│ └── index.js
├── module-b
│ └── index.js
└── module-c
└── index.js

要求处理完以后的数据结构如下

{
  "en": {
    "moduleA": {
      "functionA": {
        "subFunctionA": {
          "grandFunc": {
            "canvas": "canvas"
          },
          "input": "input"
        },
        "body": "body",
        "subFunctionB": {
          "p": "p"
        }
      },
      "functionB": {
        "h1": "h1"
      },
      "nav": "nav",
      "video": "video",
      "subFunctionC": {
        "p": "p"
      }
    },
    "moduleB": {
      "footer": "footer"
    },
    "moduleC": {
      "header": "header"
    }
  },
  "zh": {
    "moduleA": {
      "functionA": {
        "subFunctionA": {
          "grandFunc": {
            "canvas": "画布"
          },
          "input": "输入框"
        },
        "body": "主体",
        "subFunctionB": {
          "p": "段落"
        }
      },
      "functionB": {
        "h1": "一级标题"
      },
      "nav": "导航",
      "video": "视频",
      "subFunctionC": {
        "p": "段落"
      }
    },
    "moduleB": {
      "footer": "底部"
    },
    "moduleC": {
      "header": "头部"
    }
  }
}

提示:

  • index.js文件下的数据会和index/index.js的数据合并到同一层级下
  • sub-function-a/index.jssub-function-a.js下的数据经过处理后应该在同一层级下
  • 请将题目 fork 到自己 project 中, 完成后向 hr 反馈最新的 project link 即可

本题考点

  • 1.请使用 node.js 按照要求应用程序
  • 2.请考虑代码的可读性和复用性(规范格式, 注释, 功能粒度控制)
  • 3.本题考点: 递归, 闭包, 文件处理, 正则表达式
  • 4.返题请返 url,请在 stackblitz 的 terminal 执行 node./index.js 保证项目能正常运行且答案再返题(不要返代码或者 zip!!!) !important

思路

  • 1.node.js 的fs模块读取文件(如果是文件,递归,知道是.js文件,读取内容)
  • 2.把读取到的内容拼接到路径后面 eg:‘my-data\module-b\index.js\{“footer”:“footer”}’
  • 3.‘把路径字符串以\’分割成数组
  • 4.根据数组转对象
  • 参考:https://cloud.tencent.com/developer/article/1383945?from=15425&areaSource=102001.1&traceId=lkiJc-SzTADSMLpTwkjXC
  • https://www.coder.work/article/7265065

代码

var fs = require('fs');
var join = require('path').join;
let obj = {};
function getJsonFiles(jsonPath) {
  let jsonFiles = [];
  let jsonFiles2 = [];
  function findJsonFile(path) {
    let files = fs.readdirSync(path);
    files.forEach(function (item, index) {
      let fPath = join(path, item);
      let stat = fs.statSync(fPath);
      if (stat.isDirectory() === true) {
        findJsonFile(fPath);
      }
      if (stat.isFile() === true) {
        //读取文件
        let data = fs.readFileSync(fPath);
        var regex3 = /\{(.+)\}/g;

        const arr = data
          .toString()
          .replace(/\ +/g, '')
          .replace(/[\r\n]/g, '')
          .match(regex3);

        let value = {};
        let value2 = {};
        arr.map((item) => {
          const obj = strToJson(item);
          for (let key in obj) {
            value[key] = obj[key].zh;
            value2[key] = obj[key].en;
          }
        });

        jsonFiles.push(fPath + '\\' + JSON.stringify(value));
        jsonFiles2.push(fPath + '\\' + JSON.stringify(value2));
      }
    });
  }
  findJsonFile(jsonPath);
  console.log('jsonFiles', jsonFiles);
  let arr = [];
  let arr2 = [];
  jsonFiles.map((item) => {
    arr.push(item.split('\\').splice(1));
  });
  jsonFiles2.map((item) => {
    arr2.push(item.split('\\').splice(1));
  });
  let newObj = processInput(arr);
  let newObj2 = processInput(arr2);
  const newdd = objM(newObj); //把index:{ddd:aaa}拿出来,并把空的index:{}删除
  const newdd2 = objM(newObj2); //把index:{ddd:aaa}拿出来,并把空的index:{}删除
  let allObj = {};
  allObj.zh = newdd;
  allObj.en = newdd2;
  console.log('obj', allObj);
  console.log('obj', JSON.stringify(allObj));
}

function objM(newObj) {
  Object.keys(newObj).forEach((item, index) => {
    if (item === 'index') {
      let flag = empty(newObj['index']);
      if (flag) {
        Reflect.deleteProperty(newObj, item);
      } else {
        let result = getResult(newObj[item]);
        for (let key in result) {
          newObj[key] = result[key];
          Reflect.deleteProperty(newObj, item);
        }
      }
    } else {
      if (newObj[item].constructor === Object) {
        objM(newObj[item]);
      }
    }
  });
  return newObj;
}
//转对象
function processInput(propsToAdd) {
  var resultingObj = {},
    propArr;

  for (var i = 0, len = propsToAdd.length; i < len; i += 1) {
    let arr = [];
    propsToAdd[i].forEach((item) => {
      if (item.indexOf('-') != -1) {
        const name = tf(item);
        arr.push(name);
      } else {
        arr.push(item);
      }
    });
    propArr = arr;
    createRec(propArr, resultingObj);
  }

  return resultingObj;
}

function createRec(propArr, resultingObj, index) {
  var prop;
  for (var j = index || 0, len1 = propArr.length; j < len1; j += 1) {
    if (propArr[j].indexOf('.js') == -1) {
      //没找到
      prop = propArr[j];
    } else {
      //找到
      prop = propArr[j].split('.')[0];
    }
    if (!resultingObj[prop]) {
      resultingObj[prop] = {};
    }

    if (propArr[j + 1].indexOf('{') != -1) {
      if (prop.indexOf('index') != -1) {
        const value = JSON.parse(propArr[j + 1]);
        for (let key in value) {
          resultingObj[key] = value[key];
        }
        j += 1;
      } else {
        resultingObj[prop] = propArr[j + 1];
        j += 1;
      }
    } else {
      createRec(propArr, resultingObj[prop], j + 1);
      j = len1;
    }
  }
}

//正则匹配转换
function tf(str) {
  var re = /-(\w)/g;
  str = str.replace(re, function ($0, $1) {
    return $1.toUpperCase();
  });
  return str;
}

function strToJson(str) {
  var json = eval('(' + str + ')'); //将字符串转json对象
  return json;
}

function empty(obj) {
  for (let key in obj) {
    return false; //非空
  }
  return true; //为空
}
//多级嵌套的对象转一级对象
function getResult(data, result = {}) {
  for (let key in data) {
    if (data[key] && typeof data[key] == 'object') {
      getResult(data[key], result);
    } else {
      result[key] = data[key];
    }
  }
  return result;
}

getJsonFiles('./my-data/');

你可能感兴趣的:(javascript,html,json)