// 原始数据
let arr = [{ "label": "费用名称及项目", "id": -1, "children": [{ "label": "名称", "id": -5, "children": [] }, { "label": "项目", "id": -6, "children": [] }] }, { "label": "公式", "id": -2, "children": [] }, { "label": "金额", "id": -3, "children": [] }, { "label": "备注", "id": -4, "children": [] }]
function flatten(arr) {
let ress = [];
arr.map((item) => {
// console.log(item, Array.isArray(item), item.children && item.children.length !== 0);
if (item.children && item.children.length !== 0) {
ress = ress.concat(flatten(item.children));
} else {
ress.push(item);
}
});
return ress;
}
let newArr = flatten(arr)
// console.log('数组扁平化', newArr, JSON.stringify(newArr));
let add = [];
let treeChandeArr = JSON.parse(JSON.stringify(newArr));
// console.log('数组扁平化', add);
for (let j = 0; j < treeChandeArr.length; j++) {
let item = treeChandeArr[j];
item.prop = 'prop' + (j + 1).toString();
add.push(item);
}
console.log('获取到添加prop的数组', JSON.stringify(add));
// 原始数据
let arr = [{ "label": "费用名称及项目", "id": -1, "children": [{ "label": "名称", "id": -5, "children": [] }, { "label": "项目", "id": -6, "children": [] }] }, { "label": "公式", "id": -2, "children": [] }, { "label": "金额", "id": -3, "children": [] }, { "label": "备注", "id": -4, "children": [] }]
// 计算后的
let back = [{ "label": "名称", "id": -5, "children": [], "prop": "prop1" }, { "label": "项目", "id": -6, "children": [], "prop": "prop2" }, { "label": "公式", "id": -2, "children": [], "prop": "prop3" }, { "label": "金额", "id": -3, "children": [], "prop": "prop4" }, { "label": "备注", "id": -4, "children": [], "prop": "prop5" }]
function initData(arr) { // 第一种
if (arr.length) {
for (var i = 0; i < arr.length; i++) {
arr[i].prop = ''
if (back.length) {
for (let j = 0; j < back.length; j++) {
let itemprop = back[j];
console.log(itemprop)
if (arr[i].id == itemprop.id) {
arr[i].prop = itemprop.prop
}
}
}
if (arr[i].children.length) { // 如果有 children 则继续递归遍历
this.initData(arr[i].children);
}
}
}
return arr
}
let a = initData(arr)
console.log(a, JSON.stringify(a))