寻找树最后一项父节点,及id匹配项
var obj = {name: "a1", type: 1, children: [], expend: true}
var arr2 = [
{name: "a1", type: 1, children: [], expend: true},
{
name: "a1",
type: 1,
children: [],
expend: true
}
]
var arr = [
{name: "a1", type: 1, children: [], expend: true, id: "1"},
{
name: "a1",
id: "2",
type: 1,
children: [
{
id: "2.1",
name: "a1",
type: 1,
children: [{name: "a1", type: 1, children: [], expend: true, id: "2.1.1"}],
expend: true
},
{
id: "2.2",
name: "a1",
type: 1,
children: [{name: "a1", type: 1, children: [], expend: true}],
expend: true
}
],
expend: true
}
]
var tempParent = arr
function format(obj, id) {
if (id) {
checkId(arr, obj, id)
} else {
if (arr.length === 0) {
arr.push(obj)
} else {
checkLast(arr, obj)
}
}
}
function checkLast(arr, obj) {
var length = arr.length
if (arr[length - 1].expend && arr[length - 1].children.length > 0) {
tempParent = arr[length - 1].children
checkLast(arr[length - 1].children, obj)
} else {
tempParent.push(obj)
}
}
function checkId(arr, obj, id) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
arr[i].children.push(obj)
return
} else {
checkId(arr[i].children, obj, id)
}
}
}
format(obj, "2.1")
console.log(arr)