javascript - 如何将具有表示数字列表(“1.1.1”)的键的对象转换为多维数组
问题描述
让我们考虑一下我有以下普通对象:
var numberedList = {
"1": "Text of 1",
"1.1": ["array of 1.1"],
"1.2": {
key: "object of 1.2"
},
"1.1.1": 999,
"1.2.1": true,
"1.2.2": function () {
return "function of 1.2.2";
},
"1.3": null,
"2": 2
}
我想完成以下多维数组:
为了简单地解释我自己:
[
["1",
[
[
[
"1.1",
[
"1.1.1"
]
]
],
[
[
"1.2",
[
"1.2.1",
"1.2.2"
]
],
],
"1.3"
]
],
"2"
]
最终数组:
[
[
"Text of 1",
[
[
[
["array of 1.1"],
[
999
]
]
],
[
[
{
key: "object of 1.2"
},
[
true,
function()
{
return "function of 1.2.2";
}
]
],
],
null
]
],
2
]
请注意,最深的元素不会包装到数组中。
如何在纯香草 js中执行通用递归函数来完成此任务?
主要目标是执行一个console.group()
调用树,例如在console.groupEnd()
每个树分支的末尾也会调用。如果顶部的对象执行这些控制台调用,那么帮助我完成这个也是一个奖励。
解决方案
这是我的解决方案,
var numberedList = { "1": "Text of 1", "1.1": ["array of 1.1"], "1.2": { key: "object of 1.2" }, "1.1.1": 999, "1.2.1": true, "1.2.2": function () { return "function of 1.2.2"; }, "1.3": null, "2": 2 }
function gen(numberedList) {
let result = Object.keys(numberedList).reduce((res, key) => {
let indexs = key.split(".");
let lastindex = indexs.pop()
indexs.reduce((res, i) => res[i], res)[lastindex] = [key]
return res
}, []);
result.shift(); // Removing first item, Becouse index count from 0;
return result
}
console.log(gen(numberedList))
您需要创建一个trimer
函数来修剪此结果,以删除括号 ([])
推荐阅读
- android - Flutter 返回 `lifecycle-common-java8.jar (androidx.lifecycle:lifecycle-common-java8:2.0.0)` 错误
- django - Django ManytoManyField 的限制选项
- android - 什么是在本地为 iOS/Android 存储大数据的最佳方式
- r - 事后三向交互方差分析
- ruby - 了解 Chef 环境属性
- java - 属性中带有 ObjectId 的 MongoDB 文档
- linux - Unix diff 与上下文并排
- r - 创建日期的 df 以传递给 purrr 函数
- python - 使用python从pandas中的嵌套字典中获取特定键的值
- html - CSS 未应用于 Angular 应用程序