数组扁平化及树形数据添加属性

// 原始数据
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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑞朋哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值