I need to convert a js object to another object for passing onto a server post where the names of the keys differ for example
var a = {
name : \"Foo\",
No there is no function in either library that explicitly renames keys. Your method is also the fastest (see jsperf tests.) Your best bet, if possible, is to refactor either the client side or server side code so the objects are the same.
As user2387823 was saying above
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');
I have a transformation operator and would just like to apply it to all keys. I forked pimvdb's fiddle to produce a simple example. In this case it Capitalizes the key. And it dynamically builds the keymap, which I needed to assure works (thanks JSFiddle).
Here is the changed code:
var keymap = {};
_.each(a, function(value, key) {
var oldkey = key;
key = capitalize(key);
keymap[oldkey] = key;
});
_.each(a, function(value, key) {
key = keymap[key] || key;
b[key] = value;
});
Fiddle: http://jsfiddle.net/mr23/VdNjf/
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/