Javascript将underscore_case转换为lowerCamelCase

时间:2017-03-04 12:46:48

标签: javascript

我有一个API可以返回undescore_case中的响应,而前面则使用lowerCamerlCase。我还使用NodeJS在前端和后端之间进行调解。

我想将任何类型的Javascript变量转换为lowerCamelCase,为此我写了这个函数:

function transform(any) {
    if(Array.isArray(any)) {
        any.forEach((v, k) => any[k] = transform(v));
    } else if(typeof any === "object" && any != null) {
        Object.keys(any).forEach(key => {
            let t = key.replace(/_\w/g, (m) => m[1].toUpperCase());
            if(t !== key) {
                any[t] = transform(any[key]);
                delete any[key];
            }
        });
    }

    return any;
}

它有效,但我想知道是否有任何方法可以让它更快。

我生成此数据例如:

let list = [];
for(let i = 0; i < 1000; i++)
    list.push({
        some_thing: {
            aa_bb: 1,
            bb_cc: 2,
            cc_dd: 3
        },
        stuff_underscore: "aaa",
        ordinary: 1
    });

使用以下方法进行测试:

console.time("test");
transform(list);
console.timeEnd("test");

那么,有没有办法让它更快?

2 个答案:

答案 0 :(得分:2)

您可以使用public static void main(String[] args) { try { KeyStore clientStore = KeyStore.getInstance("PKCS12"); clientStore.load(new FileInputStream("d:\\certs\\api\\xx.p12"), "W*53as_G".toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientStore, "W*53as_G".toCharArray()); KeyManager[] kms = kmf.getKeyManagers(); KeyStore trustStore = KeyStore.getInstance("JKS"); trustStore.load(new FileInputStream("c:\\jdk1.8.0_51\\jre\\lib\\security\\cacerts"), "changeit".toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); TrustManager[] tms = tmf.getTrustManagers(); SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(kms, tms, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); URL url = new URL("https://apis2s.ee/test"); HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection(); urlConn.setRequestProperty("Authorization", "Basic " + Base64.encode("andrey:pass_1".getBytes())); urlConn.setUseCaches(false); urlConn.setAllowUserInteraction(true); urlConn.setRequestProperty("Pragma", "no-cache"); urlConn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); urlConn.setRequestProperty("Content-length", Integer.toString("id=1288210&ip=127.0.0.1".length())); urlConn.setDoOutput( true ); urlConn.setRequestProperty( "Content-Length", Integer.toString( jsonParams.length() )); PrintStream out = new PrintStream(urlConn.getOutputStream()); out.print("id=1288210&ip=127.0.0.1"); out.flush(); out.close(); StringBuilder builder = new StringBuilder(); int responseCode = urlConn.getResponseCode(); builder.append(responseCode) .append(" ") .append(urlConn.getResponseMessage()) .append("\n"); InputStream res = urlConn.getInputStream(); Scanner in = new Scanner(res); String responseStr = ""; while(in.hasNextLine()) { String s = in.nextLine(); responseStr+=s; } System.out.println(builder); System.out.println("responseStr: " + responseStr); } catch (KeyStoreException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } } 的第二个参数在反序列化期间执行此转换。与反序列化后行走结果相比,这可能会节省一些时间:

JSON.parse

答案 1 :(得分:0)

你正在做(至少)三件非常慢的事情:在循环中重复条件检查,正则表达式和删除对象键。

const transform = obj => {
  const keys = Object.keys(obj);
  const newKeys = keys.map(k => {
    const [first, ...rest] = k.split('_');
    return first + rest.reduce((acc, s) => {
      return acc + s[0].toUpperCase() + s.slice(1);
    }, '');
  });
  return newKeys.reduce((acc, k, i) => {
    acc[k] = obj[keys[i]];
    return acc;
  }, {});
};

现在我们使用字符串函数而不是正则表达式,构造一个新对象而不是修改一个对象,而不是在转换函数中进行任何条件检查(这些应该在你调用之前发生)。