我有一个来自数据源的关联数组(我无法控制),如下所示:
{
"name": "foo",
"children": {
"#1": {
"count": 2,
"children": {
"#2": {
"count": 4,
"children": {
"#5": ...
}
},
"#4": {
"count": 3,
"children": {
"#6": ...
}
}
}
}
}
}
正如您所看到的,它是一个使用id作为键的不断扩展的树结构。我想将其转换为普通数组,因此我可以在浏览器中使用lodash,以便更轻松/更快地操作。
结果应如下所示:
{
"name": "foo",
"children": [
{
"id": "#1",
"count": 2,
"children": [
{
"id": "#2",
"count": 4,
"children": [...]
},
{
"id": "#4",
"count": 3,
"children": [...]
}
]
},
]
}
转换对象不是问题,但我无法解决的是如何递归地执行此操作,以便结构不会变平并且所有子项都在正确的父项下。我在这里阅读了以前的帖子,但找不到任何有助于这种转换的方法。
答案 0 :(得分:2)
您可以使用Object.keys(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)和递归函数,如此
var a = {
"name": "foo",
"children": {
"#1": {
"count": 2,
"children": {
"#2": {
"count": 4,
"children": {
"#5": {}
}
},
"#4": {
"count": 3,
"children": {
"#6": {}
}
}
}
}
}
}
function convertKeysToArray(obj) {
if (obj.children !== undefined) {
var arr = []
Object.keys(obj.children).forEach(function(key) {
var child = obj.children[key];
convertKeysToArray(child);
child.id = key;
arr.push(child)
})
obj.children = arr;
}
}
convertKeysToArray(a)
console.log(JSON.stringify(a, null, " "))
var a = {
"name": "foo",
"children": {
"#1": {
"count": 2,
"children": {
"#2": {
"count": 4,
"children": {
"#5": {}
}
},
"#4": {
"count": 3,
"children": {
"#6": {}
}
}
}
}
}
}
function convertKeysToArray(obj) {
if (obj.children !== undefined) {
var arr = []
Object.keys(obj.children).forEach(function(key) {
var child = obj.children[key];
convertKeysToArray(child);
child.id = key;
arr.push(child)
})
obj.children = arr;
}
}
convertKeysToArray(a)
so.log(a)

<pre id="so"></pre>
<script>
var so = {
log: function (obj) {
document.getElementById("so").innerHTML = JSON.stringify(obj, null, " ");
}
}
</script>
&#13;