项目遇到了js递归的问题,不知道怎么解
问题1,colorArr 的第N项添加到data的第N项及其子元素,子元素的子元素
var colorArr = ['orange', 'green']
var data = [{
name: 'a',
children: [{
name: 'a1',
children: [{
name: 'aa1'
}]
}]
}, {
name: 'b',
children: [{
name: 'b1'
}]
}]
期待的结果
[{
name: 'a',
color: 'orange',
children: [{
name: 'a1',
color: 'orange'
children: [{
name: 'aa1',
color: 'orange'
}]
}]
}, {
name: 'b',
color: 'green',
children: [{
name: 'b1',
color: 'green'
}]
}]
问题2,根据最后一层子元素的value值,计算出他父元素的value值,以及父元素的父元素的value值,一直计算到最上层的value值
var data = [{
name: 'a',
children: [{
name: 'a1',
children: [{
name: 'aa1',
value: 1
}, {
name: 'aa2',
value: 1
}]
}, {
name: 'a11',
children: [{
name: 'aAA',
value: 2
}]
}]
}, {
name: 'b',
children: [{
name: 'b1',
value:3
}]
}]
期待的结果
var data = [{
name: 'a',
value: 4,
children: [{
name: 'a1',
value: 2,
children: [{
name: 'aa1',
value: 1
}, {
name: 'aa2',
value: 1
}]
}, {
name: 'a11',
value: 2,
children: [{
name: 'aAA',
value: 2
}]
}]
}, {
name: 'b',
value: 3,
children: [{
name: 'b1',
value:3
}]
}]
5 回复
自己顶一下,第一道题我自己解决了,第二题尚未解决,大家对这个没兴趣嘛
后序遍历,算出所有孩子的value,再算出父亲的value,直到根
function traversal(node) {
if (node.children && node.children.length) {
let ret = 0;
for (let i = 0; i < node.children.length; i++) {
traversal(node.children[i]);
ret += node.children[i].value;
}
node.value = ret;
}
}
@theanarkh 谢谢大佬,原来不是递归能解决的问题了,我去看看后序遍历
随便写写,自己优化一下
var data = [
{
name: "a",
children: [
{
name: "a1",
children: [
{
name: "aa1",
value: 1,
},
{
name: "aa2",
value: 1,
},
],
},
{
name: "a11",
children: [
{
name: "aAA",
value: 2,
},
],
},
],
},
{
name: "b",
children: [
{
name: "b1",
value: 3,
},
],
},
];
var computed = (list) => {
let count = 0;
for (const item of list) {
if (item.children) {
item.value = computed(item.children);
}
count += item.value;
}
return count;
};
computed(data);
console.log(data);
@lyt308012546 谢谢大佬