Joh*_*hji 0 javascript recursion nested-loops multidimensional-array
我有这样的 json 对象
[
{"id" : 1, "parentid" : null},
{"id" : 2, "parentid" : null},
{"id" : 3, "parentid" : 2},
{"id" : 4, "parentid" : 3}
]
Run Code Online (Sandbox Code Playgroud)
我想让它像这样嵌套在javascript中
[
{"id" : 1, "parentid" : null},
{"id" : 2, "parentid" : null, "childs":
[{"id" : 3, "parentid" : 2, "childs":
[{"id": 4, "parentid" : 3}]}]
}
]
Run Code Online (Sandbox Code Playgroud)
我需要使用递归函数还是只需一个简单的循环即可完成?实现这一目标最有效的方法是什么?
function
为此,您必须使用递归。简单的循环将不起作用,因为在一个级别和最高级别中可以有n
多个。这是您可以使用的功能objects
array
n
var a = [{
"id": 1,
"parentid": null
},
{
"id": 2,
"parentid": null
},
{
"id": 3,
"parentid": 2
},
{
"id": 4,
"parentid": 3
}
]
function getNestedChildren(arr, parent) {
var out = []
for(var i in arr) {
if(arr[i].parentid == parent) {
var children = getNestedChildren(arr, arr[i].id)
if(children.length) {
arr[i].children = children
}
out.push(arr[i])
}
}
return out
}
console.log(getNestedChildren(a))
Run Code Online (Sandbox Code Playgroud)
链接:http://oskarhane.com/create-a-nested-array-recursively-in-javascript/