1.递归将扁平数据改为树形结构
//递归函数,为当前元素找到父元素
findFather: function (a, b) {
if (a.parent_id === b.id) { //判断是否是该根元素儿子
if (!b.children) {
b.children = []
}
b.children.push(a)
} else {
var leng = b.children.length
for (var k = 0; k < leng; k++) {
this.findFather(a, b.children[k])
}
}
},
2.递归将子元素的某个字段值累加到父级上
recursiveCount: function (tree, key) {
if (!tree.children) {
return tree[key] ? tree[key] : 0;
}
for (var i = 0; i < tree.children.length; i++) {
var childTree = tree.children[i];
tree[key] = parseFloat(tree[key] ? tree[key] : 0) + parseFloat(this.recursiveCount(childTree, key));
}
return tree[key] ? tree[key] : 0;
},
3.递归改变树形结构数据的每一条数据
function setValue (arrays) {
for (var i = 0; i < arrays.length; i++) {
var item = arrays[i];
item.a = item.b + item.c;
//判断item.children是否为数组
if (Array.isArray(item.children)) {
setValue(item.children); //递归调用setValue函数
}
}
}
let data = [{ a: 1, b: 2, c: 3, children: [{ a: 1, b: 2, c: 3, children: [{ a: 1, b: 2, c: 3 }, { a: 1, b: 2, c: 3, children: [{ a: 1, b: 2, c: 3 }] }] }] }]
console.log(JSON.stringify(data));
setValue(data);
console.log(JSON.stringify(data));