JavaScript 資料由駝峰結構轉下劃線結構

法子發表於2024-03-16
// 資料轉換
function recursionFunc (data) {
  if (data && typeof (data) == 'object') {
    var obj
    if (Array.isArray(data)) {
      obj = []
      for (var item of data) {
        obj.push(recursionFunc(item))
      }
    } else {
      obj = {}
      for (var key in data) {
        var newKey = changeKey(key) // 字串轉換
        obj[newKey] = recursionFunc(data[key])
      }
    }
    return obj
  } else {
    return data
  }
}

// 字串轉換
function changeKey (str) {
  var arr = [...str]
  var arrCopy = [...str]
  var index = 0
  var length = arrCopy.length
  for (var i of arrCopy) {
    var front = index - 1 >= 0 ? arrCopy[index - 1].charCodeAt(0) : null
    var behind = index + 1 < length ? arrCopy[index + 1].charCodeAt(0) : null
    var num = i.charCodeAt(0)

    if (num >= 65 && num <= 90) {
      if (front && (front >= 97 && front <= 122 || behind && behind >= 97 && behind <= 122)) {
        arr[index] = '_' + arr[index].toLowerCase()
      } else {
        arr[index] = arr[index].toLowerCase()
      }
    }
    index++
  }
  return arr.join('')
}

使用:var result = recursionFunc(data)

var data = {
  createTime: '2024-12-11 23:09:06',
  updateTime: null,
  aCar: [
    {
      fillType: { code: 'HH', desc: '我的狀態很好 aBC' },
      isFavorite: true,
      memberList: [
        {
          nameText: '高院長',
          age: 32,
          phoneNumber: '18564768765',
          friendsList: [
            {
              firstName: '三',
              familyNmae: '張',
              address: null
            },
            {
              firstName: '四',
              familyNmae: '李',
              address: null
            }
          ]
        }
      ]
    },
    {
      fillType: { code: 'GOOD', desc: 'fasfdsa 范德薩範范德薩范德薩 dfsa' },
      isFavorite: false,
      memberList: [
        {
          nameText: '劉主任',
          age: 28,
          phoneNumber: '18564768765',
          friendsList: [
            {
              firstName: '三',
              familyNmae: '張',
              address: '廣東省深圳市南山區南頭街道建工村28號 A602'
            },
            {
              firstName: '四',
              familyNmae: '李',
              address: null
            }
          ]
        }
      ]
    },
    {
      fillType: { code: 'BAD', desc: '讓我去讓我去' },
      isFavorite: null,
      memberList: [
        {
          nameText: '王科長',
          age: 45,
          phoneNumber: '13299999999',
          friendsList: [
            {
              firstName: '五',
              familyNmae: '呂',
              address: ''
            },
            {
              firstName: '六',
              familyNmae: '金',
              address: null
            }
          ]
        }
      ]
    },
  ],
  otherID: '555555555555',
  ID: '324242432432342',
  id: '908897878797787',
  IdNumber: '766766666666',
  IDNumber: '887777777777',
  myIDNumber: '444445555555',
  wKK: [
  ],
  waitForMe: {
  },
  user: {
    nickName: '哇咔咔',
    orderList: [{
      orderId: '12345',
      orderName: '剪刀',
      vipPirce: '32.2',
      price: '40'
    }],
    phone: '17654365467',
    searchCount: true,
    size: 10,
    total: 2,
    countId: null,
    current: 1,
    hitCount: false,
    maxLimit: null,
    optimizeCountSql: true,
    orders: [],
    pages: 1
  },
  a1: '4767373633',
  tearch: true,
  countNumber: 5,
  holdStatus: 'isBack',
  errorMsg: "",
  extra: null,
  isSuccess: true,
  msg: "ok",
  path: null,
  timestamp: 1710472476396,
}

var result = recursionFunc(data)

console.log('result:', result)

計算結果 result:

{
  "create_time": "2024-12-11 23:09:06",
  "update_time": null,
  "a_car": [
    {
      "fill_type": { "code": "HH", "desc": "我的狀態很好 aBC" },
      "is_favorite": true,
      "member_list": [
        {
          "name_text": "高院長",
          "age": 32,
          "phone_number": "18564768765",
          "friends_list": [
            { "first_name": "三", "family_nmae": "張", "address": null },
            { "first_name": "四", "family_nmae": "李", "address": null }
          ]
        }
      ]
    },
    { "fill_type": { "code": "GOOD", "desc": "fasfdsa 范德薩範范德薩范德薩 dfsa" }, "is_favorite": false, "member_list": [{ "name_text": "劉主任", "age": 28, "phone_number": "18564768765", "friends_list": [{ "first_name": "三", "family_nmae": "張", "address": "廣東省深圳市南山區南頭街道建工村28號 A602" }, { "first_name": "四", "family_nmae": "李", "address": null }] }] },
    { "fill_type": { "code": "BAD", "desc": "讓我去讓我去" }, "is_favorite": null, "member_list": [{ "name_text": "王科長", "age": 45, "phone_number": "13299999999", "friends_list": [{ "first_name": "五", "family_nmae": "呂", "address": "" }, { "first_name": "六", "family_nmae": "金", "address": null }] }] }],
  "other_id": "555555555555",
  "id": "908897878797787",
  "id_number": "887777777777",
  "my_id_number": "444445555555",
  "w_kk": [],
  "wait_for_me": {},
  "user": {
    "nick_name": "哇咔咔",
    "order_list": [{ "order_id": "12345", "order_name": "剪刀", "vip_pirce": "32.2", "price": "40" }],
    "phone": "17654365467",
    "search_count": true,
    "size": 10,
    "total": 2,
    "count_id": null,
    "current": 1,
    "hit_count": false,
    "max_limit": null,
    "optimize_count_sql": true,
    "orders": [],
    "pages": 1
  },
  "a1": "4767373633",
  "tearch": true,
  "count_number": 5,
  "hold_status": "isBack",
  "error_msg": "",
  "extra": null,
  "is_success": true,
  "msg": "ok",
  "path": null,
  "timestamp": 1710472476396
}

相關文章