记录一下自己在工作中遇到的处理数组的方法
场景、用法、代码都奉上
不定期的持续更新
1、两数组对象对比,去除相同ID的值
let arr1=[{id:1,name:'天地影像图'},{id:2,name:'ESRI影像图'}]
let arr2=[{id:1,name:'天地影像图'},{id:3,name:'天地电子图'},{id:44,name:'山东遮罩'},{id:45,name:'世界青岛图'},]
let resArr=arr2.filter(item=>!arr1.some(ele=>ele.id===item.id))
//reaArr 结果为[{"id": 3,"name": "天地电子图"},{"id": 44,"name": "山东遮罩"},{"id": 45,"name": "世界青岛图"}]
2.树状结构,已知val递归获取item
export const getTreeItem = (tree, { treeKey, val }) => {
let node = {}
const getNode = (tree, { treeKey, val }) => {
for (let i = 0; i < tree.length; i++) {
const item = tree[i];
if (item[treeKey] === val) {
node = item
} else if (item.children?.length > 0) {
getNode(item.children, { treeKey, val })
}
}
}
getNode(tree, { treeKey, val })
return node
}
3.树状结构,查找当前层级的所有上级
const treeFindPath = (tree = searchLayerTree, func, path = []) => {
for (const data of tree) {
path.push({ key: data.key, title: data.title, children: data.children })
if (func(data)) return path
if (data.children) {
const findChildren = treeFindPath(data.children, func, path)
if (findChildren.length) return findChildren
}
path.pop()
}
return []
}
// 使用方式 findKey为要目标、searchLayerTree为树结构数组
let rankTree = treeFindPath(searchLayerTree, data => data.key === findKey)
4.树状结构,查找第一个leaf为true的对象(情景:用于antd默认展开指定节点—第一个leaf为true的节点)
//创建空数组用于存储
const dataList = []
//使用递归的方式进行循环遍历
const findFirstNode = (resChildren) => {
if (resChildren.length === 0) return
for (var i = 0; i < resChildren.length; i++) {
if (resChildren[i].leaf) {
dataList.push(resChildren[i])
} else {
findFirstNode(resChildren[i].children)
}
}
//实质上是返回了所有层级的第一个leat为true的对象集合dataList,那第一个就是dataList[0]
return dataList[0]
}
我怎么总用递归呢。。。下次想想别的办法