共计 676 个字符,预计需要花费 2 分钟才能阅读完成。
const getTreeIds = (tree: any[], nodeId: any, config: {}) => {
//tree 指标树,nodeId 节点 id
const {children = 'cityList', id = 'adCode'} = config || {}
const toFlatArray = (tree: any[], parentId: never[]) => {return tree.reduce((t: any, _: Record<string, any>) => {const child = _[children]
return [
...t,
parentId ? {..._, parentId} : _,
...(child && child.length ? toFlatArray(child, _[id]) : [])]
}, [])
}
const getIds = (flatArray: any[]) => {let ids = [nodeId]
let child = flatArray.find((_: Record<string, any>) => _[id] === nodeId)
while (child && child.parentId) {ids = [child.parentId, ...ids]
// eslint-disable-next-line @typescript-eslint/no-loop-func
child = flatArray.find((_: Record<string, any>) => _[id] === child.parentId)
}
return ids
}
return getIds(toFlatArray(tree, []))
}
正文完