我有一个来自数据源的关联数组(我不控制),像这样:
{
"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": [...]
}
]
},
]
}
转换对象不是问题,但我无法解决的是如何递归地做到这一点,使结构不会变平,所有子节点都在正确的父节点下。我浏览了之前的文章,但是没有找到任何对这种转换有帮助的
您可以使用Object。键(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>