js遍历多层对象的键值对

最项目需要用到el-tree,后端竟然不会构造数据,最后还得自己来搞

testHandle() {
  console.log(‘==================‘)
  let list1 = {  //后端只能处理成这样
    气象: {
      极飞: {
        IWS7: {
          巴里坤1号站: ‘xxx‘,
          巴里坤2号站: ‘xxx‘,
          气象站: ‘xxx‘
        },
        IWS3: {
          新果园温湿度仪: ‘xxx‘
        }
      }
    },
    视频: {
      极飞: {
        IFC16S: {
          新果园苗情监测: ‘xxx‘,
          老果园苗情监测: ‘xxx‘
        }
      }
    }
  }
  let newList1 = []
  // tree1 子系统
  let tree1 = list1
  Object.keys(tree1).forEach(item1 => {
    // console.log(item1, tree1[item1]) //气象 {极飞: {…}}
    // tree2 设备商
    let tree2 = tree1[item1]
    let child2 = []
    Object.keys(tree2).forEach(item2 => {
      // console.log(item2, tree2[item2]) //极飞 {IWS7: {…}, IWS3: {…}}
      // tree3 型号
      let tree3 = tree2[item2]
      let child3 = []
      Object.keys(tree3).forEach(item3 => {
        // console.log(item3, tree3[item3]) //IFC16S {新果园苗情监测: "xxx", 老果园苗情监测: "xxx"}
        // tree4 设备
        let tree4 = tree3[item3]
        let child4 = []
        Object.keys(tree4).forEach(item4 => {
          // console.log(item4, tree4[item4]) //新果园苗情监测 xxx
          let one = { label: item4, value: tree4[item4] }
          // console.log(one)  //{label: "巴里坤1号站", value: "xxx"}
          child4.push(one)
        })
        let one = { label: item3, value: item3, children: child4 }
        // console.log(one) //{label: "IWS7", value: "IWS7", children: Array(3)}
        child3.push(one)
      })

      let one = { label: item2 + ‘设备‘, value: item2, children: child3 }
      // console.log(one) //{label: "极飞设备", value: "极飞", children: Array(2)}
      child2.push(one)
    })

    // let subSysName = this.subSysName
    let subSysName = {
      气象: ‘田间气象‘,
      土壤: ‘墒情分析‘,
      视频: ‘苗请监测‘,
      井电: ‘井电能效‘,
      灌溉: ‘智慧灌溉‘,
      施肥: ‘智能施肥‘
    }

    let one = { label: subSysName[item1] + ‘子系统‘, value: item1, children: child2 }
    // console.log(one) //{label: "田间气象子系统", value: "气象", children: Array(1)}
    newList1.push(one)
  })
  console.log(newList1) //ok
},

lebel要套不同的内容,不好迭代,暂时手动嵌套,不知道还有没有更优雅的写法

js遍历多层对象的键值对

上一篇:自定义 View 绘制基础 HenCoder 总结-1 [MD]


下一篇:快来让你的网页色彩绚丽--linear-gradient与radial-gradient