当前位置:网站首页>JS tree structure, find out the parent set of each layer it belongs to according to the ID of the inner layer
JS tree structure, find out the parent set of each layer it belongs to according to the ID of the inner layer
2022-07-24 10:50:00 【French speaking pig】
Recently, there was a small demand , There is a tree structure , Then know one of the inner layers id, We need to find the parent node of each layer it belongs to , Including itself, of course . Because I haven't done this before , Then I thought about it , Perfect implementation , Then I also found a third-party library . Next, let's talk about my thoughts and handling methods
First, the last test data
const tree = [
{
id: '1',
parentId: 0,
name: ' Shandong Province ',
children: [
{
id: '1-1',
parentId: '1',
name: ' Jinan City ',
children: [
{
id: '1-1-1',
parentId: '1-1',
name: ' Calendar area ',
children: []
},
{
id: '1-1-2',
parentId: '1-1',
name: ' Licheng District ',
children: []
}
]
},
{
id: '1-2',
parentId: '1',
name: ' Heze City ',
children: [
{
id: '1-2-1',
parentId: '1-2',
name: ' Yuncheng county ',
children: []
},
{
id: '1-2-2',
parentId: '1-2',
name: ' Juancheng county ',
children: []
}
]
}
]
}
]Mode one : Do it yourself
The process is divided into two steps :
① I will flatten the tree structure first , Process as peer
② Traverse the flat data above , First, according to the known id Find the first , Then according to its parentId Look again , Know where to find it parentId by 0( No superior ) Until , It is also a recursive operation
Then two methods are pasted below , Corresponding to the above two steps
// 1. First flatten the tree structure , Process as peer
function flatTree(tree) {
const list = []
tree.forEach(item => {
const o = JSON.parse(JSON.stringify(item))
if(o.children) delete o.children
list.push(o)
if(item.children && item.children.length) {
list.push(...flatTree(item.children))
}
})
return list
}
// 2. Traverse the flat data above , First, according to id Find the first , Then according to its parentId Look again , Know where to find it parentId by 0 Until , It is also a recursive operation
function getParentAreas(pid, list) {
const target = []
const o = list.find(item => item.id == pid) || {}
if(JSON.stringify(o) != '{}') target.push(o)
if(o.parentId) target.push(...getParentAreas(o.parentId, list))
return target
}The next step is to test :
console.log(getParentAreas('1-1-2', flatTree(tree)), '----->>>')
// [
// { id: '1-1-2', parentId: '1-1', name: ' Licheng District ' },
// { id: '1-1', parentId: '1', name: ' Jinan City ' },
// { id: '1', parentId: 0, name: ' Shandong Province ' }
// ]Because it's based on the inside , So what we find is from the inner layer to the outer layer , If you want to turn around , Again reverse Just a second
Then you can optimize the above code , Because two methods are used to process data , So I write these two methods into a class , We execute the above method when instantiating , Get the data we need directly
class FindArrsById {
constructor(id, tree) {
this.id = id
this.flatArr = this.flatTree.call(this, tree)
this.parentAreas = this.getParentAreas.call(this, this.id, this.flatArr)
this.getParentNames.bind(this)
}
flatTree(tree) {
const list = []
tree.forEach(item => {
const o = JSON.parse(JSON.stringify(item))
if(o.children) delete o.children
list.push(o)
if(item.children && item.children.length) {
list.push(...this.flatTree(item.children))
}
})
return list
}
getParentAreas(pid, list) {
const target = []
let o = list.find(item => item.id == pid) || {}
if(JSON.stringify(o) != '{}') target.push(o)
if(o.parentId) target.push(...this.getParentAreas(o.parentId, list))
return target
}
// This method is to get a set of fields
getParentNames(key) {
return this.parentAreas.map(item => item[key]).reverse()
}
}Test it :
console.log(new FindArrsById('1-1-2', tree).getParentNames('name'), '----->>>')
// [ ' Shandong Province ', ' Jinan City ', ' Licheng District ' ]Mode two : use xe-utils Third party Library
xe-utils GitHub Address https://github.com/x-extends/xe-utils
file : https://vxetable.cn/xe-utils/#/
install :
npm install xe-utilsUse :
const XEUtiles = require('xe-utils') // Or use ES6 Medium import Fine
let searchTree = XEUtiles.searchTree(tree, item => item.id == '1-1-2', { children: 'children' })
console.log(searchTree, '----->>>')
// [
// {
// id: '1',
// parentId: 0,
// name: ' Shandong Province ',
// children: [
// {
// id: '1-1',
// parentId: '1',
// name: ' Jinan City ',
// children: [
// {
// id: '1-1-2',
// parentId: '1-1',
// name: ' Licheng District ',
// children: []
// }
// ]
// }
// ]
// }
// ]This is also a powerful library , I don't actually use this , This is what I found after I finished it , There are many ways , Various data 、 Method conversion , With 6 It's really convenient .
But generally speaking, I can handle it by myself , If it's not too complicated , You don't have to use it .
边栏推荐
- Hash, bitmap and bloom filter for mass data De duplication
- Redis cache settings, similar to putifabsent function
- 划分数据2
- Distributed lock implementation scheme (glory collection version)
- Sentinel three flow control effects
- N-tree, page_ Size, database strict mode modification, and the difference between delete and drop in the database
- IEPE vibration sensor synchronous signal acquisition card /icp synchronous data network acquisition module
- Disk storage chain B-tree and b+ tree
- 零基础学习CANoe Panel(7)—— 文件选择(PathDiaglog)
- App automation and simple environment construction
猜你喜欢

零基础学习CANoe Panel(6)—— 开关/显示控件(Switch/Indicator)

《nlp入门+实战:第二章:pytorch的入门使用 》

Sentinel flow control quick start
![[class, abstraction and inheritance]](/img/eb/4c8d0c86b1320015b2ccb0289f4f00.png)
[class, abstraction and inheritance]

How to build a node development environment efficiently

二叉树基础知识概览

ECCV 2022 | 清华提出首个嵌入光谱稀疏性的Transformer

1184. 公交站间的距离 : 简单模拟题

Filter the data with signal processing toolbox software

Hongmeng's first note
随机推荐
Qt程序最小化托盘后,再弹出个msgbox,点击确定后程序退出问题解决
NLP introduction + practice: Chapter 2: introduction to pytorch
实时天气API
Zero basic learning canoe panel (4) -- button
QT application prevents multiple opening, that is, single instance operation
MySQL - normal index
小熊派学习——内核开发
[dish of learning notes dog learning C] detailed operator
数组元素移除问题
UVM——双向通信
零基础学习CANoe Panel(8)—— 数据/文本编辑控件(Hex/Text Editor )
分布式事务处理方案大 PK!
MySQL - multi column index
谷歌联合高校研发通用模型ProteoGAN,可设计生成具有新功能的蛋白质
redis 缓存设置,实现类似putIfAbsent功能
[dish of learning notes dog learning C] evaluation expression
二分查找法
Hash, bitmap and bloom filter for mass data De duplication
Daily three questions 7.21
Arduino + AD9833 waveform generator