84

我从这样的 API 返回 JSON:

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

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

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

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

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

还是我可以映射原始数组或以某种方式对其进行转换?

4

21 回答 21

114

如果您使用lodash而不是下划线,则可以:

_.mapKeys(obj, (v, k) => _.camelCase(k))

这会将TitleCase和转换snake_casecamelCase. 请注意,它不是递归的。

于 2015-09-07T15:08:26.707 回答
96

这是一个可靠的递归函数,可以正确地对 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
    }
}
于 2014-10-06T11:38:07.730 回答
49

你可以使用这个递归函数(使用 lodash 和 ES6)来做到这一点:

import { camelCase } from 'lodash';

const camelizeKeys = (obj) => {
  if (Array.isArray(obj)) {
    return obj.map(v => camelizeKeys(v));
  } else if (obj != null && obj.constructor === Object) {
    return Object.keys(obj).reduce(
      (result, key) => ({
        ...result,
        [camelCase(key)]: camelizeKeys(obj[key]),
      }),
      {},
    );
  }
  return obj;
};

测试:

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
   }
}
于 2018-05-31T09:12:09.487 回答
22

要将普通对象的键从更改snake_casecamelCase 递归尝试以下操作
(使用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中测试

注意:也递归地适用于数组中的对象

于 2017-02-01T23:31:42.203 回答
13

使用 lodash 和 ES6,这将递归地将所有键替换为驼峰式:

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) 
    };
  }, {});
};      
于 2017-10-06T04:09:00.780 回答
7

只需使用驼峰

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

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

于 2021-04-05T22:44:20.060 回答
6

这是axios 拦截器的一个很好的用例

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

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)
    }
}

这是一个使用 React/axios 的更长示例的要点。

于 2017-11-07T23:54:43.053 回答
3

使用 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 };
  }, {});
};
于 2018-03-13T02:41:04.907 回答
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" } ] }
于 2020-05-14T10:38:48.873 回答
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);

属性转换器(jsfiddle)

诀窍是将对象作为对象属性的数组来处理。

于 2012-10-17T10:55:07.437 回答
2

该解决方案基于上面的纯 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>

于 2017-09-03T11:26:55.880 回答
2

这是您可能想尝试的方便库: 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)
于 2019-04-12T22:15:36.383 回答
1

我需要一个接受数组或对象的通用方法。这就是我正在使用的(我借用了 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"}
于 2014-06-18T15:00:30.013 回答
1

用 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 };
  }, {});
};
于 2017-12-08T23:23:50.007 回答
1

使用 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
}

于 2020-06-20T13:47:00.017 回答
1

类似于 @brandonscript 的解决方案,但以更多 ES6 功能的方式:

const camelCaseString = str => (
  (str.charAt(0).toLowerCase() + str.slice(1) || str).toString() 
);

const objectToCamelCase = val => {
  if (typeof val != 'object' || val === null) {
    return val;
  }
 
  if (val instanceof Array) {
    return val.map(objectToCamelCase);
  }
 
  return Object.keys(val)
    .filter(prop => val.hasOwnProperty(prop))
    .map(prop => ({[camelCaseString(prop)]: objectToCamelCase(val[prop])}))
    .reduce((prev, current) => ({...prev, ...current}))
};

// Example:
let converted = objectToCamelCase({UserId: 1, Hobbies: [{Id: 1, Label: "Read"}], Name: "John Doe"});

console.log(converted)

于 2021-10-14T00:25:12.880 回答
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;  
}
于 2017-09-10T09:57:00.113 回答
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;
}
于 2018-02-14T05:24:40.883 回答
0

建立在 goredwards 的答案(它没有正确处理数组字段)

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
}
于 2019-08-01T14:42:13.637 回答
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;
};
于 2021-05-17T21:48:30.947 回答
-1

将对象键转换为带有深度的 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;
}
于 2020-01-23T09:38:13.490 回答