Is there any way to rename js object keys using underscore.js

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/


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

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');

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/