<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
const arr = [
{
id:'1',
title:'1',
parentId: '0',
type: null,
children: []
},
{
id:'2',
title:'2',
type: null,
parentId: '0',
children: [
{
id:'2-1',
title:'2-1',
type: null,
parentId: '2',
children: []
}
]
},
{
id:'3',
title:'3',
type: null,
parentId: '0',
children: [
{
id:'3-1',
title:'3-1',
type: 1,
parentId:'3',
children: []
}
]
},
{
id:'4',
title:'4',
type: null,
parentId: '0',
children: []
},
{
id:'5',
title:'5',
type: null,
parentId: '0',
children: [
{
id:'5-1',
title:'5-1',
type: null,
parentId: '5',
children: [
{
id:'5-1-1',
title:'5-1-1',
type: 1,
parentId:'5-1',
children: []
}
]
},
{
id:'5-2',
title:'5-2',
type: 1,
parentId: '5',
children: [
{
id:'5-2-1',
title:'5-2-1',
type: 1,
parentId:'5-2',
children: []
}
]
}
]
},
{
id:'6',
title:'6',
type: 1,
parentId: '0',
children: [
{
id:'6-1',
title:'6-1',
type: 1,
parentId: '6',
children: [
{
id:'6-1-1',
title:'6-1-1',
type: 1,
parentId:'6-1',
children: [
{
id:'6-1-1-1',
title:'6-1-1-1',
type: 1,
parentId:'6-1-1',
children: []
}
]
}
]
}
]
}
]
let parentLoopIds = []
// 通过id找父id(包括自己)
function getParentIdList(array, id) {
let parentArray = [];
if (array.length === 0) {
return parentArray;
}
const recursion = function (arrayNew, id) {
for (let i = 0; i < arrayNew.length; i++) {
let node = arrayNew[i];
if (node.id === id) {
parentArray.unshift(id);
recursion(array, node.parentId);
break;
} else {
if (!!node.children) {
recursion(node.children, id);
}
}
}
return parentArray;
}
let arrayNew = array;
parentArray = recursion(arrayNew, id);
return parentArray;
}
function childToParentLoop(data, setKey, compareKey, compareVal) {
data.map(dataItem => {
if (dataItem.type === 1) {
let tempArr = getParentIdList(JSON.parse(JSON.stringify(arr)), dataItem.id)
// 过滤自己
tempArr = tempArr.filter(tempArrItem => tempArrItem !== dataItem.id)
// 合并
parentLoopIds = parentLoopIds.concat(tempArr)
}
if (dataItem.children && dataItem.children.length) {
childToParentLoop(dataItem.children, setKey, compareKey, compareVal)
}
})
// 去重
parentLoopIds = parentLoopIds.filter((currentValue, index, arrSelf) => {
return arrSelf.indexOf(currentValue, 0) === index;
});
return parentLoopIds
}
console.log('arr', arr)
console.log('setTreeList', childToParentLoop(JSON.parse(JSON.stringify(arr)), 'type', 'type', 1))
</script>
</html>
JS数组对象:递归通过子节点属性设置父节点属性
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 前言 团队合作临摹饿了么移动端APP,选择了现在比较热门的React框架,虽然项目功能还不完善,但是在开发的过程中...
- 1、插件地址:https://gitee.com/grapess/layui[https://gitee.com/...
- 一、DOM文档对象模型 二、获取元素方法 1、根据ID获取 2、根据标签名获取 3、通过H5新增方法获取 4、获取...
- 节点属性 在文档对象模型 (DOM) 中,每个节点都是一个对象。DOM 节点有三个重要的属性 : nodeName...