vuvivian's blog

越努力,越幸运.

定义了一个按钮的列表,列表是一个树形结构,现在有个问题是,需要遍历树形的每个子节点,给每个子节点生成一个btnId,最终返回一个key为btnId, 值为子节点数据的对象。

数据结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const buttonArray = [{
tag: "button",
attrs: {
string: "新建",
accesskey: "create",
children: []
}
},
{
tag: "buttonGroup",
attrs: {
string: "新建",
accesskey: "createGroups",
children:[
{
tag: "button",
attrs: {string: "新建1", accesskey: "create1"}
},{
tag: "button",
attrs: {string: "新建2", accesskey: "creat2"}
}
]
}
},
{
tag: "button",
attrs: {
string: "编辑",
accesskey: "edit",
children: []
}
}]

执行代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function _eventGroup(data, buttonList) {
data.map((item, index)=>{
if (Array.isArray(item.attrs.children) && item.attrs.children.length > 0) {
_eventGroup(item.attrs.children, buttonList);
} else {
const btnId = `advantedBtn_${index}`
item.attrs.btnId = btnId;
buttonList[btnId] = item.attrs;
}
})
return buttonList;
}

let buttonList = {};
_eventGroup(buttonArray, buttonList)

执行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
advantedBtn_0: {
string: "新建1",
accesskey: "create1",
children: [],
btnId: "advantedBtn_0"
},
advantedBtn_1: {
string: "新建2",
accesskey: "creat2",
children: [],
btnId: "advantedBtn_1"
},
advantedBtn_2: {
string: "编辑",
accesskey: "edit",
children: [],
btnId: "advantedBtn_2"
}
}
本文最后更新于 天前,文中所描述的信息可能已发生改变