gpt4 book ai didi

Javascript 树标签/级别

转载 作者:太空宇宙 更新时间:2023-11-04 15:57:36 29 4
gpt4 key购买 nike

var myArray = [{
title: "Title 1",
children: [{
title: "Title 1.1",
children: [{
title: "Title 1.1.1"
}]
}, {
title: "Title 1.2",
children: []
}]
},
{
title: "Title 2",
children: [{
title: "Title 2.1",
children: [{
title: "Title 2.1.1"
}]
}, {
title: "Title 2.2",
children: [{
title: "Title 2.2.1"
}]
}]
}
];

所以我有一个与此类似的数组。标题是随机的,但我想要得到的是级别,例如

{ title: 'Title 2.2 (or any othe random title)', level: '2.2', children:[...]}

我希望这是递归的,并且 lodash 解决方案将受到高度赞赏。谢谢。

最佳答案

您可以使用迭代和递归方法。

function addLevel(array, levels) {
levels = levels || [];
array.forEach(function (o, i) {
o.level = levels.concat(i + 1).join('.');
if (Array.isArray(o.children)) {
addLevel(o.children, levels.concat(i + 1));;
}
});
}

var myArray = [{ title: "Title 1", children: [{ title: "Title 1.1", children: [{ title: "Title 1.1.1" }] }, { title: "Title 1.2", children: [] }] }, { title: "Title 2", children: [{ title: "Title 2.1", children: [{ title: "Title 2.1.1" }] }, { title: "Title 2.2", children: [{ title: "Title 2.2.1" }] }] }];

addLevel(myArray);

console.log(myArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于Javascript 树标签/级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42562743/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com