代码改变世界

JavaScript 数据由驼峰结构转下划线结构

2024-03-16 14:55  法子  阅读(86)  评论(0编辑  收藏  举报
// 数据转换
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
}