vue json嵌套 转换成平面 一维 不嵌套

240 阅读1分钟
readJson (obj, map, prepose = '') {
      if (Object.prototype.toString.call(obj) === '[object Array]') {
        for (const key of obj.keys()) {
          try {
            if (typeof obj[key] === 'string') {
              map.set(prepose + key, obj[key])
            } else {
              this.readJson(obj[key], map, prepose + key + '.')
            }
          } catch (e) {
            console.log('readArray', e)
          }
        }
      } else {
        for (const key in obj) {
          try {
            if (typeof obj[key] === 'string') {
              map.set(prepose + key, obj[key])
            } else {
              this.readJson(obj[key], map, prepose + key + '.')
            }
          } catch (e) {
            console.log('readElse', e)
          }
        }
      }
    }

//调方法 

let map = new Map()//obj是要转换的
this.readJson(obj, map)
let arr = []
for (const key of map.keys()) {
              arr.push({
                guid: '',
                id: '',
                name: key,
                value: map.get(key)
              })
            }
console.log(arr)

原对象:

要改变成

envTable: [ // 环境变量
        {
          guid: '',
          id: '',
          name: 'name',
          value: 'test'
        },
        {
          guid: '',
          id: '', 
          name: 'version',
          value: '1.0.0'
        },....
      ],