So, I need to transform all keys in array from underscore to camel space in js. That is what I need to do before send form to server. I'm using Angular.js
and I want to represent it as a filter (but I think it's not rly important in this case). Anyway, here is a function I've created.
.filter('underscoreToCamelKeys', function () {
return function (data) {
var tmp = [];
function keyReverse(array) {
angular.forEach(array, function (value, key) {
tmp[value] = underscoreToCamelcase(key);
});
return tmp;
}
var new_obj = {};
for (var prop in keyReverse(data)) {
if(tmp.hasOwnProperty(prop)) {
new_obj[tmp[prop]] = prop;
}
}
return new_obj;
};
function underscoreToCamelcase (string) {
return string.replace(/(\_\w)/g, function(m){
return m[1].toUpperCase();
});
}
})
Here I will try to explain how it works, because it looks terrible at first.
underscoreToCamelcase
function just reverting any string in underscore to came case, except first character (like this some_string => someString
)
So, as I said earlier, I should revert all keys to camel case, but as you understant we can't simply write
date[key] = 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 values, those data will be dissapear
array
some_key1
=> value
,
some_key2
=> value
returns as
someKey2
=> value
So how can I fix that? I have a suggestion to check if those value exists and if it is add some special substring, like this
some_key1
=> value
,
some_key2
=> value
value
=> someKey1
,
zx99value
=> someKey2
and after all parse it for zx99, but it I think I`m going crazy... Maybe some one have a better solution in this case?
Important! Them main problem is not just to transform some string to camel case, but do it with array keys!