从对api端点的调用中,我得到了以下嵌套对象数组,这是一个目录树
const tree = [
{
label: "OTHER",
children: [],
},
{
label: "PARENT/",
children: [
{
label: "strat end/",
children: [
{
label: "startEnd",
children: [
{
label: "Inner1",
children: [
{
label: "Inner2",
children: [
{
label: "Inner3",
children: [],
},
],
},
],
},
],
},
],
},
],
},
];
我还有这个代币列表
const tokens = [
'PARENT',
'strat end',
'startEnd',
'Inner1',
'Inner2',
'Inner3',
'Inner4'
]
我需要在标记列表中为每个对象创建的标签属性中添加值为true的扩展属性
预期结果应如下
谢谢你的建议
const expectedTree = [
{
label: "OTHER",
children: [],
},
{
label: "PARENT/",
expaned: true,
children: [
{
label: "strat end/",
expaned: true,
children: [
{
label: "startEnd",
expaned: true,
children: [
{
label: "Inner1",
expaned: true,
children: [
{
label: "Inner2",
expaned: true,
children: [
{
label: "Inner3",
expaned: true,
children: [],
},
],
},
],
},
],
},
],
},
],
},
];
您可以在令牌上使用reduce
方法,然后使用find
在每个级别上获取与标签匹配的对象。
const tree = [{"label":"OTHER","children":[]},{"label":"PARENT/","children":[{"label":"strat end/","children":[{"label":"startEnd","children":[{"label":"Inner1","children":[{"label":"Inner2","children":[{"label":"Inner3","children":[]}]}]}]}]}]}]
const tokens = ["PARENT","strat end","startEnd","Inner1","Inner2","Inner3","Inner4"]
tokens.reduce((r, e) => {
const o = r.find(({label}) => label.startsWith(e));
if (o) {
o.expanded = true;
return o.children
}
return r
}, tree);
console.log(tree)
假设:
const tokens = [
'PARENT',
'strat end',
'startEnd',
'Inner1',
'Inner2',
'Inner3',
'Inner4'
]
是指向扩展的最深节点的路径,并且您不介意更改您可以做的原始数据结构:
let nodes = tree;
for (const token of tokens) {
const node = nodes.find(node => node.label == token);
node.expaned = true;
nodes = node.children;
}
就像我已经说过的,这确实改变了原来的结构。然而,根据您的情况,这可能不是问题。