Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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",     amount: 55,     reported : false,     ...     <snip/>     ...     date : "10/01/2001"     }  

needs to turn into

a = {   id : "Foo",   total : 55,   updated: false,   ...   <snip/>   ...    issued : "10/01/2001"   } 

where I have lookup obj available for mapping all the keys

var serverKeyMap = {     name : "id",     amount : "total",     reported : "updated",      ...     date : "issue"     } 

Is there a function available in underscore.js or jQuery that I can use that does this functionality?

thanks

like image 548
claya Avatar asked Jan 05 '12 18:01

claya


People also ask

Can you rename a key in an object JavaScript?

To rename a key in an object:Use bracket notation to assign the value of the old key to the new key. Use the delete operator to delete the old key. The object will contain only the key with the new name.

Can you use underscores in JavaScript?

Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications.

What does underscore do in js?

js is a JavaScript library which provides utility functions for common programming tasks. It is comparable to features provided by Prototype. js and the Ruby language, but opts for a functional programming design instead of extending object prototypes.


1 Answers

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/

like image 198
Samir Aguiar Avatar answered Sep 30 '22 18:09

Samir Aguiar