一只甜甜圈
您可以创建递归函数,每次您的对象结构更改时都会调用该函数以重新计算树中每个元素的位置。function recalc(data, prev = '') { data.forEach((e, i) => { let dot = prev ? '.' : ''; let number = prev + dot + (i + 1); if (e.children) { recalc(e.children, number) } if (e.title) { e.title.number = number } })}const data1 = [{"title":{"number":1},"children":[{"title":{"number":1.1}},{"title":{"number":1.2}},{"title":{"number":1.3}},{"title":{"number":1.4}},{"title":{"number":1.5}}]},{"title":{"number":2},"children":[{"title":{"number":2.1}},{"title":{"number":2.2},"children":[{"title":{"number":"2.2.1"}},{"title":{"number":"2.2.2"}},{"title":{"number":"2.2.3"}},{"title":{"number":"2.2.4"}}]},{"title":{"number":2.3}},{"title":{"number":2.4}}]},{"title":{"number":3},"children":[]}]recalc(data1);console.log(data1)const data2 = [{"title":{"number":1},"children":[{"title":{"number":1.1}},{"title":{"number":1.2}},{"title":{"number":1.5}}]},{"title":{"number":2},"children":[{"title":{"number":2.1}},{"title":{"number":2.2},"children":[{"title":{"number":"2.2.3"}},{"title":{"number":"2.2.4"}}]},{"title":{"number":2.3}},{"title":{"number":2.4}}]},{"title":{"number":3},"children":[{title: {}, children: [{title: {}}, {title: {}}]}]}]recalc(data2);console.log(data2)