将返回的JSON对象属性转换为(较低的第一个)camelCase

时间:2012-10-17 10:03:45

标签: javascript jquery json underscore.js

我从这样的API返回JSON:

Contacts: [{ GivenName: "Matt", FamilyName:"Berry" }]

为了保持这与我的代码样式(camelCase - 小写首字母)一致,我想转换数组以产生以下内容:

 contacts: [{ givenName: "Matt", familyName:"Berry" }]

最简单/最好的方法是什么?创建一个新的Contact对象并迭代返回的数组中的所有联系人?

var jsonContacts = json["Contacts"],
    contacts= [];

_.each(jsonContacts , function(item){
    var contact = new Contact( item.GivenName, item.FamilyName );
    contacts.push(contact);
});

或者我可以映射原件或以某种方式转换它吗?

20 个答案:

答案 0 :(得分:54)

这是一个可靠的递归函数,可以正确地使用所有JavaScript对象的属性:

function toCamel(o) {
  var newO, origKey, newKey, value
  if (o instanceof Array) {
    return o.map(function(value) {
        if (typeof value === "object") {
          value = toCamel(value)
        }
        return value
    })
  } else {
    newO = {}
    for (origKey in o) {
      if (o.hasOwnProperty(origKey)) {
        newKey = (origKey.charAt(0).toLowerCase() + origKey.slice(1) || origKey).toString()
        value = o[origKey]
        if (value instanceof Array || (value !== null && value.constructor === Object)) {
          value = toCamel(value)
        }
        newO[newKey] = value
      }
    }
  }
  return newO
}

测试:

var obj = {
  'FirstName': 'John',
  'LastName': 'Smith',
  'BirthDate': new Date(),
  'ArrayTest': ['one', 'TWO', 3],
  'ThisKey': {
    'This-Sub-Key': 42
  }
}

console.log(JSON.stringify(toCamel(obj)))

输出:

{
    "firstName":"John",
    "lastName":"Smith",
    "birthDate":"2017-02-13T19:02:09.708Z",
    "arrayTest": [
        "one", 
        "TWO", 
        3
    ],
    "thisKey":{
        "this-Sub-Key":42
    }
}

答案 1 :(得分:53)

如果您使用lodash而不是下划线,则会执行以下操作:

COUNT()

这会将_.mapKeys(obj, (v, k) => _.camelCase(k)) TitleCase都转换为snake_case。请注意,它不是递归的。

答案 2 :(得分:15)

要将普通对象的密钥从snake_case更改为camelCase 递归 ,请尝试以下方法
(使用Lodash):

function objectKeysToCamelCase(snake_case_object) {
  var camelCaseObject = {};
  _.forEach(
    snake_case_object,
    function(value, key) {
      if (_.isPlainObject(value) || _.isArray(value)) {     // checks that a value is a plain object or an array - for recursive key conversion
        value = objectKeysToCamelCase(value);               // recursively update keys of any values that are also objects
      }
      camelCaseObject[_.camelCase(key)] = value;
    }
  )
  return camelCaseObject;
};

在此PLUNKER

中进行测试

注意:对于数组中的对象也是递归工作的

答案 3 :(得分:8)

谢谢其他我这样做(使用lodash和ES6的递归函数):

const obj = {
  'FirstName': 'John',
  'LastName': 'Smith',
  'BirthDate': new Date(),
  'ArrayTest': ['one', 'TWO', 3],
  'ThisKey': {
    'This-Sub-Key': 42
  }
}

console.log(JSON.stringify(camelizeKeys(obj)))

测试:

{  
   "firstName": "John",
   "lastName": "Smith",
   "birthDate": "2018-05-31T09:03:57.844Z",
   "arrayTest":[  
      "one",
      "TWO",
      3
   ],
   "thisKey":{  
      "thisSubKey": 42
   }
}

输出:

1  1/5  1/10  1/15  1/20 … 1/290  1/295  1/300

答案 4 :(得分:5)

使用lodash和ES6,这会将所有密钥递归替换为camelcase:

简写:

const camelCaseKeys = (obj) => ((!_.isObject(obj) && obj) || (_.isArray(obj) && obj.map((v) => camelCaseKeys(v))) || _.reduce(obj, (r, v, k) => ({ ...r, [_.camelCase(k)]: camelCaseKeys(v) }), {}));

展开:

const camelCaseKeys = (obj) => {
  if (!_.isObject(obj)) {
    return obj;
  } else if (_.isArray(obj)) {
    return obj.map((v) => camelCaseKeys(v));
  }
  return _.reduce(obj, (r, v, k) => {
    return { 
      ...r, 
      [_.camelCase(k)]: camelCaseKeys(v) 
    };
  }, {});
};      

答案 5 :(得分:3)

有一个不错的npm模块。 https://www.npmjs.com/package/camelcase-keys

npm install camelcase-keys
const camelcaseKeys = require( "camelcase-keys" );

camelcaseKeys( { Contacts: [ { GivenName: "Matt", FamilyName: "Berry" } ] }, { deep: true } );

将返回...

{ contacts: [ { givenName: "Matt", familyName: "Berry" } ] }

答案 6 :(得分:2)

只需使用驼峰

humps.camelize('hello_world');
humps.camelizeKeys(object, options); // will work through entire object

https://www.npmjs.com/package/humps

答案 7 :(得分:2)

我接受了挑战并认为我弄明白了:

var firstToLower = function(str) {
    return str.charAt(0).toLowerCase() + str.slice(1);
};

var firstToUpper = function(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
};

var mapToJsObject = function(o) {
    var r = {};
    $.map(o, function(item, index) {
        r[firstToLower(index)] = o[index];
    });
    return r;
};

var mapFromJsObject = function(o) {
    var r = {};
    $.map(o, function(item, index) {
        r[firstToUpper(index)] = o[index];
    });
    return r;
};


// Map to
var contacts = [
    {
        GivenName: "Matt",
        FamilyName: "Berry"
    },
    {
        GivenName: "Josh",
        FamilyName: "Berry"
    },
    {
        GivenName: "Thomas",
        FamilyName: "Berry"
    }
];

var mappedContacts = [];

$.map(contacts, function(item) {
    var m = mapToJsObject(item);
    mappedContacts.push(m);
});

alert(mappedContacts[0].givenName);


// Map from
var unmappedContacts = [];

$.map(mappedContacts, function(item) {
    var m = mapFromJsObject(item);
    unmappedContacts.push(m);
});

alert(unmappedContacts[0].GivenName);

Property converter (jsfiddle)

技巧是将对象作为对象属性数组处理。

答案 8 :(得分:1)

此解决方案基于上面的普通js解决方案,使用loadash和保留数组(如果作为参数传递)并且仅更改

function camelCaseObject(o) {
    let newO, origKey, value
    if (o instanceof Array) {
        newO = []
        for (origKey in o) {
            value = o[origKey]
            if (typeof value === 'object') {
                value = camelCaseObject(value)
            }
            newO.push(value)
        }
    } else {
        newO = {}
        for (origKey in o) {
            if (o.hasOwnProperty(origKey)) {
                newO[_.camelCase(origKey)] = o[origKey]
            }
        }
    }
    return newO
}

// Example
const obj = [
{'my_key': 'value'},
 {'Another_Key':'anotherValue'},
 {'array_key':
   [{'me_too':2}]
  }
]
console.log(camelCaseObject(obj))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

答案 9 :(得分:1)

这是axios interceptors

的一个很好的用例

基本上,定义一个客户端类并附加一个转换请求/响应数据的前/后拦截器。

export default class Client {
    get(url, data, successCB, catchCB) {
        return this._perform('get', url, data, successCB, catchCB);
    }

    post(url, data, successCB, catchCB) {
        return this._perform('post', url, data, successCB, catchCB);
    }

    _perform(method, url, data, successCB, catchCB) {
        // https://github.com/axios/axios#interceptors
        // Add a response interceptor
        axios.interceptors.response.use((response) => {
            response.data = toCamelCase(response.data);
            return response;
        }, (error) => {
            error.data = toCamelCase(error.data);
            return Promise.reject(error);
        });

        // Add a request interceptor
        axios.interceptors.request.use((config) => {
            config.data = toSnakeCase(config.data);
            return config;
        }, (error) => {
            return Promise.reject(error);
        });

        return axios({
            method: method,
            url: API_URL + url,
            data: data,
            headers: {
                'Content-Type': 'application/json',
            },
        }).then(successCB).catch(catchCB)
    }
}

这里有一个gist,其中有一个使用React / axios的较长示例。

答案 10 :(得分:0)

这是我的看法;比brandoncode的实现更具可读性且嵌套更少,并且有更多空间来处理像Date这样的边缘情况(顺便说一句,这不是处理)或null

function convertPropertiesToCamelCase(instance) {
    if (instance instanceof Array) {
        var result = [];

        for (var i = 0; i < instance.length; i++) {
            result[i] = convertPropertiesToCamelCase(instance[i]);
        }

        return result;
    }

    if (typeof instance != 'object') {
        return instance;
    }

    var result = {};

    for (var key in instance) {
        if (!instance.hasOwnProperty(key)) {
            continue;
        }

        result[key.charAt(0).toLowerCase() + key.substring(1)] = convertPropertiesToCamelCase(instance[key]);
    }

    return result;
}

答案 11 :(得分:0)

这是我为它找到的代码,虽然没有经过全面测试,但值得分享。 它比其他答案更具可读性,不确定性能。

测试一下http://jsfiddle.net/ms734bqn/1/

const toCamel = (s) => {
      return s.replace(/([-_][a-z])/ig, ($1) => {
        return $1.toUpperCase()
          .replace('-', '')
          .replace('_', '');
      });
    };

const isArray = function (a) {
  return Array.isArray(a);
};

const isObject = function (o) {
  return o === Object(o) && !isArray(o) && typeof o !== 'function';
};

const keysToCamel = function (o) {
  if (isObject(o)) {
    const n = {};

    Object.keys(o)
      .forEach((k) => {
        n[toCamel(k)] = keysToCamel(o[k]);
      });

    return n;
  } else if (isArray(o)) {
    return o.map((i) => {
      return keysToCamel(i);
    });
  }

  return o;
};

答案 12 :(得分:0)

使用lodash ...

function isPrimitive (variable) {
  return Object(variable) !== variable
}

function toCamel (variable) {
  if (isPrimitive(variable)) {
    return variable
  }

  if (_.isArray(variable)) {
    return variable.map(el => toCamel(el))
  }

  const newObj = {}
  _.forOwn(variable, (value, key) => newObj[_.camelCase(key)] = toCamel(value))

  return newObj
}

答案 13 :(得分:0)

建立在不可思议的答案(不能正确处理数组字段)上

function objectKeysToCamelCase(snake_case_object) {
  let camelCaseObject = {}
  _.forEach(
    snake_case_object,
    function(value, key) {
      if (_.isPlainObject(value)) {
        value = objectKeysToCamelCase(value)
      } else if (_.isArray(value)) {
        value = value.map(v => _.isPlainObject(v) ? objectKeysToCamelCase(v) : v)
      }
      camelCaseObject[_.camelCase(key)] = value
    },
  )
  return camelCaseObject
}

答案 14 :(得分:0)

这里是您想尝试的便捷库: https://www.npmjs.com/package/camelize2

您只需要先安装npm install --save camelize2然后

const camelize = require('camelize2')

const response = {
   Contacts: [{ GivenName: "Matt", FamilyName:"Berry" }]
}

const camelizedResponse = camelize(response)

答案 15 :(得分:0)

使用lodash,您可以这样做:

export const toCamelCase = obj => {
  return _.reduce(obj, (result, value, key) => {
    const finalValue = _.isPlainObject(value) || _.isArray(value) ? toCamelCase(value) : value;
    return { ...result, [_.camelCase(key)]: finalValue };
  }, {});
};

答案 16 :(得分:0)

接受了lodash和一些es6 +功能的挑战 这是我使用reduce函数的实现。

function deeplyToCamelCase(obj) {
  return _.reduce(obj, (camelCaseObj, value, key) => {
    const convertedDeepValue = _.isPlainObject(value) || _.isArray(value)
      ? deeplyToCamelCase(value)
      : value;
    return { ...camelCaseObj, [_.camelCase(key)] : convertedDeepValue };
  }, {});
};

答案 17 :(得分:0)

使用https://plnkr.co/edit/jtsRo9yU12geH7fkQ0WL?p=preview中的引用更新了代码 这通过将数组保持为数组(可以使用map迭代)来处理带有包含对象的数组的对象,依此类推。

function snakeToCamelCase(snake_case_object){
  var camelCaseObject;
  if (isPlainObject(snake_case_object)) {        
    camelCaseObject = {};
  }else if(isArray(snake_case_object)){
    camelCaseObject = [];
  }
  forEach(
    snake_case_object,
    function(value, key) {
      if (isPlainObject(value) || isArray(value)) {
        value = snakeToCamelCase(value);
      }
      if (isPlainObject(camelCaseObject)) {        
        camelCaseObject[camelCase(key)] = value;
      }else if(isArray(camelCaseObject)){
        camelCaseObject.push(value);
      }
    }
  )
  return camelCaseObject;  
}

答案 18 :(得分:0)

我需要一个接受数组或对象的泛型方法。这就是我正在使用的(我借用了KyorCode firstToLower()实现):

function convertKeysToCamelCase(obj) {
    if (!obj || typeof obj !== "object") return null;

    if (obj instanceof Array) {
        return $.map(obj, function(value) {
            return convertKeysToCamelCase(value);
        });
    }

    var newObj = {};
    $.each(obj, function(key, value) {
        key = key.charAt(0).toLowerCase() + key.slice(1);
        if (typeof value == "object" && !(value instanceof Array)) {
          value = convertKeysToCamelCase(value);
        }
        newObj[key] = value;
    });

    return newObj;
};

示例电话:

var contact = { GivenName: "Matt", FamilyName:"Berry" };

console.log(convertKeysToCamelCase(contact));
// logs: Object { givenName="Matt", familyName="Berry"}

console.log(convertKeysToCamelCase([contact]));
// logs: [Object { givenName="Matt", familyName="Berry"}]

console.log(convertKeysToCamelCase("string"));
// logs: null

console.log(contact);
// logs: Object { GivenName="Matt", FamilyName="Berry"}

答案 19 :(得分:-2)

将对象键深转换为camelCase。

import _ from 'lodash';

export function objectKeysToCamelCase(entity) {
    if (!_.isObject(entity)) return entity;

    let result;

    result = _.mapKeys(entity, (value, key) => _.camelCase(key));
    result = _.mapValues(result, (value) => objectKeysToCamelCase(value));

    return result;
}