首页 > 解决方案 > 多个对象

问题描述

我有一个看起来很奇怪的对象,我想把它变成一个包含多个对象的对象。(我的意思是嵌套对象中的多个对象)当前对象如下所示:

{
  'test.txt': "This is a test\r\n\r\nI hope  it'll work",
  'testy.js': 'console.log("thonk");\r\n',
  'thonk\\i swear\\egg.txt': 'am going to be happy?',    
  'thonk\\pls work.txt': 'dasdas'
}

我希望它看起来像这样:

{
  "test.txt": "This is a test\r\n\r\nI hope it'll work",
  "testy.js": "console.log('thonk');\r\n",
  "thonk": {
    "I swear": { 
        "egg.txt": "am going to be happy?" 
     },
    "pls work.txt": "dasdas"
  }
}

编辑:这是我的代码(如果需要):

var fs = require("fs");
var path = require("path");
var walk = function (dir, done) {
  var results = [];
  fs.readdir(dir, function (err, list) {
    if (err) return done(err);
    var i = 0;
    (function next() {
      var file = list[i++];
      if (!file) return done(null, results);
      file = path.resolve(dir, file);
      fs.stat(file, function (err, stat) {
        if (stat && stat.isDirectory()) {
          walk(file, function (err, res) {
            results = results.concat(res);
            next();
          });
        } else {
          results.push(file);
          next();
        }
      });
    })();
  });
};

var root = "test";
var data = {};

walk("test", function (err, results) {
  if (err) throw err;

  for (i in results) {
    data[
      results[i].replace(__dirname + "\\" + root + "\\", "")
    ] = fs.readFileSync(results[i], "utf8");
  }

  console.log(data);
});

标签: javascriptnode.jsjsonobjectnpm

解决方案


这可以通过组合来完成,Object.keys()如下Array.reduce()所示:

const source = {
  'test.txt': "This is a test\r\n\r\nI hope  it'll work",
  'testy.js': 'console.log("thonk");\r\n',
  'thonk\\i swear\\egg.txt': 'am going to be happy?',
  'thonk\\pls work.txt': 'dasdas'
}

const result = Object.keys(source).reduce((target, k) => {
  const keys = k.split('\\');
  if (keys.length == 1) {
    target[k] = source[k];
  } else {
    const nestedObj = target[keys[0]] || {};
    keys.slice(1).reduce((o, nestedKey, i) => {
      const value = i < keys.length -2 ? {} : source[k];      
      o[nestedKey] = value;
      return value;
    }, nestedObj);
    target[keys[0]] = nestedObj;
  }
  return target;
}, {});

console.log(result);


推荐阅读