zoukankan      html  css  js  c++  java
  • JavaScript JSON的key 下划线格式与驼峰格式互相转换

    // 字符串的下划线格式转驼峰格式,eg:hello_world => helloWorld
    function underline2Hump(s) {
      return s.replace(/_(\w)/g, function(all, letter) {
        return letter.toUpperCase()
      })
    }
    
    // 字符串的驼峰格式转下划线格式,eg:helloWorld => hello_world
    function hump2Underline(s) {
      return s.replace(/([A-Z])/g, '_$1').toLowerCase()
    }
    
    // JSON对象的key值转换为驼峰式
    function jsonToHump(obj) {
      if (obj instanceof Array) {
        obj.forEach(function(v, i) {
          jsonToHump(v)
        })
      } else if (obj instanceof Object) {
        Object.keys(obj).forEach(function(key) {
          var newKey = underline2Hump(key)
          if (newKey !== key) {
            obj[newKey] = obj[key]
            delete obj[key]
          }
          jsonToHump(obj[newKey])
        })
      }
    }
    
    // JSON对象的key值转换为下划线格式
    function jsonToUnderline(obj) {
      if (obj instanceof Array) {
        obj.forEach(function(v, i) {
          jsonToUnderline(v)
        })
      } else if (obj instanceof Object) {
        Object.keys(obj).forEach(function(key) {
          var newKey = hump2Underline(key)
          if (newKey !== key) {
            obj[newKey] = obj[key]
            delete obj[key]
          }
          jsonToUnderline(obj[newKey])
        })
      }
    }
    

      

  • 相关阅读:
    返回数组指针的函数形式
    zoj 2676 网络流+01分数规划
    2013 南京理工大学邀请赛B题
    poj 2553 强连通分支与缩点
    poj 2186 强连通分支 和 spfa
    poj 3352 边连通分量
    poj 3177 边连通分量
    poj 2942 点的双连通分量
    poj 2492 并查集
    poj 1523 求割点
  • 原文地址:https://www.cnblogs.com/xiadongqing/p/15661700.html
Copyright © 2011-2022 走看看