[
{
id: 1,
childNode: [
{
id: 2,
name: '哈哈哈’
}
]
},
{
id: 3,
childNode: [
{
id: 4,
name: '哈哈哈’
}
]
}
]
如果傳入一個id = 2,那么返回他的父級索引值,加上他自己的索引
如果傳入一個id = 1,那么返回他自己的索引,他子節點索引為空
怎么寫個遞歸呢
function indexesOf(data, id) { for(let i = 0;i<data.length;i++) { const item = data[i]; if(item.id == id) return [i]; if(item.childNode) { const childIndexes = indexesOf(item.childNode, id); if(childIndexes) return [i].concat(childIndexes); } } }
vue中的使用
// 當前選中的節點的index,如果當前點擊節點的id是容器的子節點,那么就返回父級節點的索引,加上容器的子節點索引 activeElementIndex (state) { // 根據ID找索引值 function indexesOf (data, id) { for (let i = 0; i < data.length; i++) { const item = data[i] if (item.uuid === id) return [i] if (item.childNode && item.childNode.length > 0) { const childIndexes = indexesOf(item.childNode, id) if (childIndexes) return [i].concat(childIndexes) } } } return indexesOf(state.projectData.elements, state.activeElementUUID) }, // 根據子節點的id獲取父節點的信息 getParentInfo: (state) => (id) => { // 根據ID找父節點的id function findParentId (data, id) { let result if (!data) return for (let i = 0; i < data.length; i++) { const item = data[i] if (item.uuid === id) { result = item // 找到id相等的則返回父節點 return result } else if (item.childNode && item.childNode.length > 0) { // 如果有子集,則把子集作為參數重新執行本方法 result = findParentId(item.childNode, id) if (result) { return data[i] } } } } return findParentId(state.projectData.elements, id) }
