假如有树形数组如下:
(每个数组元素都是对象,每个对象中包含一个值为数组的children属性)
let tableData = [
{
id: 1,
children: [
{
id: 2,
children: [
{ id: 3, children: [] },
{ id: 4, children: [] },
]
},
{
id: 5,
children: [
{ id: 6, children: [] },
{ id: 7, children: [] },
]
}
]
},
{
id: 8,
children: [
{
id: 9,
children: [
{ id: 10, children: [] },
{ id: 11, children: [] },
]
},
{
id: 12,
children: [
{ id: 13, children: [] },
{ id: 14, children: [] },
]
}
]
},
]
展开树形数组(数组扁平化)
function flatten(arr) {
let result = []
for (let i = 0; i < arr.length; i++) {
result.push(arr[i]);
if (arr[i].children.length>0) {
result = result.concat(flatten(arr[i].children))
}
}
console.log(result);
return result
}
console.log(flatten(tableData))
/*[
{id: 1, children: Array(2)},
{id: 2, children: Array(2)},
{id: 3, children: Array(0)},
{id: 4, children: Array(0)},
{id: 5, children: Array(2)},
{id: 6, children: Array(0)},
{id: 7, children: Array(0)},
{id: 8, children: Array(2)},
{id: 9, children: Array(2)},
{id: 10, children: Array(0)},
{id: 11, children: Array(0)},
{id: 12, children: Array(2)},
{id: 13, children: Array(0)},
{id: 14, children: Array(0)},
] */
检查某id是否存在
function checkById(arr, id) {
let exist = false;
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
return true
} else {
if (arr[i].children.length>0) {
exist = checkById(arr[i].children, id)
if (exist) {
return exist
}
}
}
}
return exist;
}
console.log(checkById(tableData, 14));//true
根据 id 查找当前元素 所在层级的数组
function findById(arr,id) {
let result
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
result = arr
return result
} else {
if (arr[i].children.length>0) {
result = findById(arr[i].children, id)
if (result) {
return result
}
}
}
}
return result//如果id不存在返回的是undefined
}
console.log(findById(tableData,14));
根据 id 删除对应数组元素
function deleteById(arr, id) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
arr.splice(i,1)
break
} else {
if (arr[i].children && arr[i].children.length) {
deleteById(arr[i].children,id)
}
}
}
}
deleteById(tableData, 7);//删除id为7的数组元素
给每个数组元素添加parentId(元素的parentId对应父元素的id)
function addParentId(arr, parentId) {
arr.forEach(item => {
item.parentId = parentId
if (item.children.length > 0) {
addParentId(item.children,item.id)
}
});
}
addParentId(tableData,0);//第二个参数是一级元素的parentId
根据当前数组元素的parentId查找当前数组元素所在父对象
function findParentNode( arr, parentId ) {//传入的parentId不能是第一级数组元素的parentId,第一级数组元素所在父对象为数组本身,无需用方法查找。
let result
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === parentId) {
result = arr[i]
return result
} else {
if (arr[i].children.length>0) {
result = findParentNode(arr[i].children, parentId)
if (result) {
return result
}
}
}
}
return result
}
console.log(findParentNode(tableData, 5));//{id: 5, children: Array(2), parentId: 1}