I have a key-value pair like
var classes = { red: 'Red', green: 'Green' };
How can I prepend each of the keys with a specific value? Could this be done using jQuery.map?
The final result I'm looking for is
classes = { 'a-red': 'Red', 'a-green': 'Green' };
map() method applies a function to each item in an array or object and maps the results into a new array. Prior to jQuery 1.6, $. map() supports traversing arrays only. As of jQuery 1.6 it also traverses objects.
To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!
Use the set() method to update a value in a Map , e.g. map. set('key', 'value') . The set() method adds or updates the element with the provided key and value and returns the Map object.
The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.
The given answers will work, but they aren't as much fun as using a purely functional construct like $.map. Here's a purely functional version:
$.extend.apply(null, $.map(classes, function(v,k) { var h = {}; h["a-" + k] = v; return h }));
This works in two steps: first, the map operates on the key-value pairs of the original object and returns a list of single-valued objects. Secondly, the $.extend function combines these all together into a single object; the .apply method is used to pass the arguments to the function as an array.
Unfortunately, the lack of a nice way to make object literals with variable key names makes this kind of ugly, and it's possibly not as efficient, but is a a nifty one-liner!
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