[英]How to add a property to a series of objects nested within an array?
从对 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'
]
我需要在 label 属性中的对象中添加值为 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: [],
},
],
},
],
},
],
},
],
},
],
},
];
假如说:
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;
}
就像我已经说过的那样,这确实会改变原始结构。 但是,根据您的情况,这可能不是问题。
您可以对令牌使用reduce
方法,然后在与 label 匹配的每个级别上find
object。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.