Is there any way to rename js object keys using underscore.js
Solution 1:
I know you didn't mention lodash and the answers already solve the problem, but someone else might take advantage of an alternative.
As @CookieMonster mentioned in the comments, you can do this with _.mapKeys
:
_.mapKeys(a, function(value, key) {
return serverKeyMap[key];
});
And the fiddle: http://jsfiddle.net/cwkwtgr3/
Solution 2:
Similar to @pimvdb, you can also do it with a _.reduce
:
_.reduce(a, function(result, value, key) {
key = map[key] || key;
result[key] = value;
return result;
}, {});
Fiddle: http://jsfiddle.net/T9Lnr/39/
Solution 3:
As far as I know there is no function built into either of these two libraries. You can make your own fairly easily, though: http://jsfiddle.net/T9Lnr/1/.
var b = {};
_.each(a, function(value, key) {
key = map[key] || key;
b[key] = value;
});
Solution 4:
You could copy the values to the new properties with standard JavaScript, and remove the original properties with omit, as follows:
a.id = a.name;
a.total = a.amount;
a.updated = a.reported;
a = _.omit(a, 'name', 'amount', 'reported');
Solution 5:
// key_map: {old_name1: new_name1, ... }
function rename_keys(object, key_map, is_picked=false){
keys = _.keys(key_map);
new_keys = _.values(key_map);
picked = _.pick(object, keys);
renamed = _.object(new_keys, _.values(picked));
if(is_picked) return renamed;
return _.chain(object).omit(keys).extend(renamed).value();
}
This may be slower than above answers.