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
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With