kidoOooOoooOOom

ゲーム開発やってます

[JS] スネークケースのstring/object keys を キャメルケースに変換

最近はガリガリ開発していてそっちでアウトプットしているので、ブログには書く頻度が減ってしまった。
今日書いたコードは糞だけど汎用性あるのでこっちにメモ

  /**
   * Convert snake case string or object keys to camel case.
   */
  convertSnakeToCamel: function(snake) {
    if (!snake) {
      return snake;
    }

    var camel;
    var that = this;
    if (typeof snake === 'string') {
      camel = snake.replace(/_./g, function(matched) {
        return matched.charAt(1).toUpperCase();
      });
      return camel;
    }

    _.each(snake, function(value) {
      if(_.isObject(value) === true) {
        return that.convertSnakeToCamel(value);
      }
    });

    for (var prop in snake) {
      if ((prop.indexOf('_') !== -1) && snake.hasOwnProperty(prop)) {
        var tmp = snake[prop];
        delete snake[prop];
        camel = this.convertSnakeToCamel(prop);
        snake[camel] = tmp;
      }
    }
    return snake;