/*
* array-树形数据
* targetId-目标id
* valueKey-用来判断的字段名
* childrenKey-子元素字段名
**/
findPatentValue(array, targetId, valueKey, childrenKey) {
if (!targetId || !Array.isArray(array)) return []
const result = []
let valid = false
const seek = (_array, _targetId) => {
let parentValue = ''
const up = (_array_, _targetId_, lastValue) => {
_array_.forEach(v => {
const val = v[valueKey]
const child = v[childrenKey]
if (val === _targetId_) {
valid = true
parentValue = lastValue
return
}
child?.length && up(child, _targetId_, val)
})
}
up(_array, _targetId)
if (parentValue) {
result.unshift(parentValue)
seek(_array, parentValue)
}
}
seek(array, targetId)
return valid ? [...result, targetId] : []
}
// 使用方法
let arr = [{
id: 1,
label: '1',
children: [{
id: 2,
label: '2',
children: [{
id: 3,
label: '3'
}]
}]
}]
this.findPatentValue(arr, 3, 'id', 'children') // [1,2,3]
|