javascript - 多个对象
问题描述
我有一个看起来很奇怪的对象,我想把它变成一个包含多个对象的对象。(我的意思是嵌套对象中的多个对象)当前对象如下所示:
{
'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);
});
解决方案
这可以通过组合来完成,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);
推荐阅读
- r - 当我应用 smote 函数来平衡类时出现错误和警告
- python-3.x - 检查列表中的项目是否在列表类型的列中可用
- python - 如何在 selenium python 中获取当前滚动高度
- hibernate - Hibernate 不使用 JPA 实体创建 PostgreSQL 模式对象
- java - 在 Java 中临时阻止打印到 System.out
- c# - RTI DDS 连接器编译失败
- r - 查找列中每个值的营业额
- python - 将小表存储在一个文件容器中的最佳数据库
- android - 警告 Adb 连接错误:现有连接被远程主机强行关闭
- java - 如何删除从哈希图生成的重复结果