Javascript camelcase to underscore

Javascript camelcase to underscore

Underscore-to-camelCase converter (and vice versa) for strings and object keys in JavaScript.

When converting object keys, it will walk the structure, converting any nested objects (or arrays of nested objects) along the way. Handy for converting JSON between JavaScript and Ruby/Rails APIs.

Takes inspiration from Ember Data and copies some utility functions from Underscore.js.

humps.camelize('hello_world') // 'helloWorld' humps.decamelize('fooBar') // 'foo_bar' humps.decamelize('fooBarBaz', < separator: '-' >) // 'foo-bar-baz' 
var object = < attr_one: 'foo', attr_two: 'bar' >humps.camelizeKeys(object); //

Arrays of objects are also converted

var array = [< attr_one: 'foo' >, < attr_one: 'bar' >] humps.camelizeKeys(array); // [< attrOne: 'foo' >, < attrOne: 'bar' >] 

It also accepts a callback which can modify the conversion behavior. For example to prevent conversion of keys containing only uppercase letters or numbers:

humps.camelizeKeys(obj, function (key, convert) < return /^[A-Z0-9_]+$/.test(key) ? key : convert(key); >); humps.decamelizeKeys(obj, function (key, convert, options) < return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options); >); 

In order to use the callback with options use the process option:

Читайте также:  Javascript угол между двумя векторами

Removes any hypens, underscores, and whitespace characters, and uppercases the first character that follows.

humps.camelize('hello_world-foo bar') // 'helloWorldFooBar'

Similar to humps.camelize(string) , but also ensures that the first character is uppercase.

humps.pascalize('hello_world-foo bar') // 'HelloWorldFooBar'

Converts camelCased string to an underscore-separated string.

humps.decamelize('helloWorldFooBar') // 'hello_world_foo_bar'

The separator can be customized with the separator option.

humps.decamelize('helloWorldFooBar', separator: '-' >) // 'hello-world-foo-bar'

By default, decamelize will only split words on capital letters (not numbers as in humps pre v1.0). To customize this behaviour, use the split option. This should be a regular expression which, when passed into String.prototype.split , produces an array of words (by default the regular expression is: /(?=[A-Z])/ ). For example, to treat numbers as uppercase:

humps.decamelize('helloWorld1', split: /(?=[A-Z0-9])/ >) // 'hello_world_1'

Same as humps.decamelize above.

Converts object keys to camelCase. It also converts arrays of objects.

Converts object keys to PascalCase. It also converts arrays of objects.

Separates camelCased object keys with an underscore. It also converts arrays of objects. See humps.decamelize for details of options.

humps is copyright © 2012+ Dom Christie and released under the MIT license.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

🐫 Underscore-to-camelCase converter (and vice versa) for strings and object keys in JavaScript.

domchristie/humps

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Underscore-to-camelCase converter (and vice versa) for strings and object keys in JavaScript.

When converting object keys, it will walk the structure, converting any nested objects (or arrays of nested objects) along the way. Handy for converting JSON between JavaScript and Ruby/Rails APIs.

Takes inspiration from Ember Data and copies some utility functions from Underscore.js.

humps.camelize('hello_world') // 'helloWorld' humps.decamelize('fooBar') // 'foo_bar' humps.decamelize('fooBarBaz', < separator: '-' >) // 'foo-bar-baz' 
var object = < attr_one: 'foo', attr_two: 'bar' >humps.camelizeKeys(object); //

Arrays of objects are also converted

var array = [< attr_one: 'foo' >, < attr_one: 'bar' >] humps.camelizeKeys(array); // [< attrOne: 'foo' >, < attrOne: 'bar' >] 

It also accepts a callback which can modify the conversion behavior. For example to prevent conversion of keys containing only uppercase letters or numbers:

humps.camelizeKeys(obj, function (key, convert) < return /^[A-Z0-9_]+$/.test(key) ? key : convert(key); >); humps.decamelizeKeys(obj, function (key, convert, options) < return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options); >); 

In order to use the callback with options use the process option:

Removes any hypens, underscores, and whitespace characters, and uppercases the first character that follows.

humps.camelize('hello_world-foo bar') // 'helloWorldFooBar'

Similar to humps.camelize(string) , but also ensures that the first character is uppercase.

humps.pascalize('hello_world-foo bar') // 'HelloWorldFooBar'

Converts camelCased string to an underscore-separated string.

humps.decamelize('helloWorldFooBar') // 'hello_world_foo_bar'

The separator can be customized with the separator option.

humps.decamelize('helloWorldFooBar',  separator: '-' >) // 'hello-world-foo-bar'

By default, decamelize will only split words on capital letters (not numbers as in humps pre v1.0). To customize this behaviour, use the split option. This should be a regular expression which, when passed into String.prototype.split , produces an array of words (by default the regular expression is: /(?=[A-Z])/ ). For example, to treat numbers as uppercase:

humps.decamelize('helloWorld1',  split: /(?=[A-Z0-9])/ >) // 'hello_world_1'

Same as humps.decamelize above.

Converts object keys to camelCase. It also converts arrays of objects.

Converts object keys to PascalCase. It also converts arrays of objects.

Separates camelCased object keys with an underscore. It also converts arrays of objects. See humps.decamelize for details of options.

humps is copyright © 2012+ Dom Christie and released under the MIT license.

About

🐫 Underscore-to-camelCase converter (and vice versa) for strings and object keys in JavaScript.

Источник

Convert javascript object camelcase keys to underscore case

If you have a property ‘foo’ its getter should be named ‘getFoo’, and if you have a property named ‘foo_bar’ its getter should be named ‘getFooBar’, however, in your example you’re mapping a boolean and booleans have special case naming conventions in java. Well, you can have an implementation for PropertyNamingStrategy that looks something like this: then in your implementation or the class that does the desrialization you can have: Solution 1: I have found the following setting works perfect when reading json with underscored attributes and using camelcasing in my models.

Transform all keys in array from underscore to camel case in js

If you use an existing library to do the camelCase transform, you can then reduce an object like so

import from 'lodash/string' const camelCaseKeys = (obj) => Object.keys(obj).reduce((ccObj, field) => (< . ccObj, [camelCase(field)]: obj[field] >), <>) 
.filter('underscoreToCamelKeys', function () < return function (data) < var tmp = <>; angular.forEach(data, function (value, key) < var tmpvalue = underscoreToCamelcase(key); tmp[tmpvalue] = value; >); return tmp; >; function underscoreToCamelcase (string) < return string.replace(/(\_\w)/g, function(m)< return m[1].toUpperCase(); >); > >) 

As an alternative solution, you could use the optional replacer parameter of the JSON.stringify method.

var result = JSON.stringify(myVal, function (key, value) < if (value && typeof value === 'object') < var replacement = <>; for (var k in value) < if (Object.hasOwnProperty.call(value, k)) < replacement[underscoreToCamelcase(k)] = value[k]; >> return replacement; > return value; >); 

Of course you’ll end up with a string and have to call JSON.parse to get the object.

Convert javascript object camelCase keys to, I want to be able to pass any javascript object containing camelCase keys through a method and return an object with underscore_case keys, mapped to the same values. So, I have this: var camelCased = And I want a method to output this: Code samplefunction camelToUnderscore(key) for(var camel in original)

Change object keys from underscore format to camelCase format

You’re unintentionally using the comma operator — although the new object is evaluated, the whole expression inside the parentheses evaluates to the final value in the comma-separated list, which is the empty object, which becomes the accumulator on the next iteration.

Don’t use the comma operator in the return , and pass <> as a second argument to reduce instead:

 const obj = < key_first: 'firstVal', key_second: 'secondVal', >; const renameKeys = obj => Object .keys(obj) .reduce((acc, key) => < const modifiedKey = key.replace(/_([a-z])/g, function f(g) < return g[1].toUpperCase(); >); return (< . acc, . < [modifiedKey]: objJavascript camelcase to underscore >, >); >, <>); console.log(renameKeys(obj));

Also, rather than using Object.keys , you might consider Object.entries instead, because [modifiedKey]: value is probably a bit clearer than [modifiedKey]: objJavascript camelcase to underscore :

const obj = < key_first: 'firstVal', key_second: 'secondVal', >;const renameKeys = obj => Object .entries(obj) .reduce((acc, Javascript camelcase to underscore) => < const modifiedKey = key.replace(/_([a-z])/g, g =>g[1].toUpperCase()); return (< . acc, . < [modifiedKey]: val >, >); >, <>);console.log(renameKeys(obj));

You can split the key name by group and use $1 & $2 where these represent group

const obj = < keyFirst: 'firstVal', keySecond: 'secondVal', >;let newObj = <>for (let keys in obj) < newObjJavascript camelcase to underscore)([A-Z])/g, '$1_$2').toLowerCase()] = objJavascript camelcase to underscore>console.log(newObj)

Converting identifier naming between camelCase and, If you truly wanted to intercept and adjust json objects between Python and Javascript you would have to rewrite functionality of the json module. Instead something like this would be equivalent and not be too much of a hit performance-wise. To convert each key in a dict camel_case =

Deserialising JSON with underscores to camel case in Java using Jackson? [duplicate]

Well, you can have an implementation for PropertyNamingStrategy that looks something like this:

import org.codehaus.jackson.map.MapperConfig; import org.codehaus.jackson.map.PropertyNamingStrategy; import org.codehaus.jackson.map.introspect.AnnotatedField; import org.codehaus.jackson.map.introspect.AnnotatedMethod; public class CustomNameStrategy extends PropertyNamingStrategy < @Override public String nameForField(MapperConfig config, AnnotatedField field, String defaultName) < return convert(defaultName); >@Override public String nameForGetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName) < return convert(defaultName); >@Override public String nameForSetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName) < return convert(defaultName); >public String convert(String defaultName) < char[] arr = defaultName.toCharArray(); StringBuilder nameToReturn = new StringBuilder(); for (int i = 0; i < arr.length; i++) < if (arr[i] == '_') < nameToReturn.append(Character.toUpperCase(arr[i + 1])); i++; >else < nameToReturn.append(arr[i]); >> return nameToReturn.toString(); > > 

then in your implementation or the class that does the desrialization you can have:

ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy(new CustomNameStrategy()); YourClass yourClass = mapper.readValue(yourJsonString, YourClass.class); 

Convert array keys from underscore_case to camelCase, Now these two functions can be used in tandem to achieve the overall goal of converting array keys from underscore to camel-case format. (JavaScript) 4944. Reference — What does this symbol mean in PHP? 935. Convert a PHP object to an associative array. 10806.

Convert JSON style properties names to Java CamelCase names with GSON

I have found the following setting works perfect when reading json with underscored attributes and using camelcasing in my models.

Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create() 

You can use the SerializedName annotation:

@SerializedName("field_name_in_json") private final String fieldNameInJava; 

Note: When you have set a FieldNamingPolicy already, SerializedName will overwrite its settings for that specific field (quite handy for special cases).

Bear in mind your example is an edge case. If you have a property ‘foo’ its getter should be named ‘getFoo’, and if you have a property named ‘foo_bar’ its getter should be named ‘getFooBar’, however, in your example you’re mapping a boolean and booleans have special case naming conventions in java. A primitive boolean property named online should have a getter named ‘isOnline’, NOT ‘getOnline’ or even worse, ‘getIsOnline’. A boolean wrapper object (i.e. Boolean) should not follow this special case and a property named ‘online’ should have a getter named ‘getOnline’.

Hence, having boolean properties with ‘is’ in the name is an edge case, where you’ll want to strip out this particular prefix during your conversion. In the reverse direction, your code may want to inspect the json object for both a raw property name as well as a ‘is_XXX’ version.

Javascript — Transform all keys in array from underscore, date Javascript camelcase to underscore = underscoreToCamelcase (key) so keyReverse function returns a reverted array, here is example. some_key => value. will be. value => someKey. and for the last I simply reverting keys and values back, to get this. someKey => value. But, as you already may understand, I got a problem, if in array exists the same …

Источник

Оцените статью