let list = [
{
childSubjectList: [],
subjectId: 1,
parentId: 0
},
{
childSubjectList: [],
subjectId: 2,
parentId: 0
},
{
childSubjectList: [],
subjectId: 3,
parentId: 1
},
{
childSubjectList: [],
subjectId: 4,
parentId: 2
},
{
childSubjectList: [],
subjectId: 5,
parentId: 4
}
]
将以上数组根据 parenId 放入父级的childSubjectList中
var array = []
var iterator1 = function (treeNodes) {
if (!treeNodes || !treeNodes.length) return
var node,
parent,
i = 0,
obj = {}
while (i < treeNodes.length) {
node = treeNodes[i++]
obj[node.subjectId] = node
if (node.parentId) {
parent = obj[node.parentId]
console.log(parent.childSubjectList);
if (parent.childSubjectList) {
parent.childSubjectList.push(node)
} else {
parent.childSubjectList = [node]
}
} else {
array.push(node)
}
}
return array
}
//list是需要转换的数组
iterator1(list)
//array是转化完成之后的数组
console.log(array);