gpt4 book ai didi

javascript - 向嵌套对象树中的 Javascript 对象添加序号

转载 作者:行者123 更新时间:2023-11-29 19:09:49 24 4
gpt4 key购买 nike

我有一个如下所示的对象,我正在寻找一种方法来为树中的每个子对象添加一个属性。也就是我想给对象加一个数,从0到n递增。我知道我可以使用递归函数遍历对象,但是由于变量范围,我无法在遍历树时使用简单的递增变量进行计数。

当前对象:

var tree = [
{
name: 'a',
children: []
},{
name: 'b',
children: [
{
name: 'c',
children: []
}
]
},
{
name: 'd',
children: [
{
name: 'e',
children: [
{
name: 'f',
children: []
},
{
name: 'g',
children: []
}
]
}
]
}
];

想要的对象:

var tree = [
{
name: 'a',
number: 0,
children: []
},{
name: 'b',
number: 1,
children: [
{
name: 'c',
number: 2,
children: []
}
]
},
{
name: 'd',
number: 3,
children: [
{
name: 'e',
number: 4,
children: [
{
name: 'f',
number: 5,
children: []
},
{
name: 'g',
number: 6,
children: []
}
]
}
]
}
];

最佳答案

您只需要在递归 函数之外设置计数器变量并在循环对象之前递增它。

var tree = [{"name":"a","children":[]},{"name":"b","children":[{"name":"c","children":[]}]},{"name":"d","children":[{"name":"e","children":[{"name":"f","children":[]},{"name":"g","children":[]}]}]}];

function addNumber(input) {
var counter = 0;

function rec(data) {
data.forEach(function(e) {
if (typeof e == 'object' && !Array.isArray(e)) {
e.number = counter++;
for (var p in e) {
if (typeof e[p] == 'object') rec(e[p])
}
}
})
}
rec(input)
}

addNumber(tree);
console.log(tree)

关于javascript - 向嵌套对象树中的 Javascript 对象添加序号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39875651/

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