Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify object using jQuery.map?

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

like image 321
Dogbert Avatar asked Oct 08 '10 12:10

Dogbert


People also ask

What is map () in jQuery?

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.

How do you update an object in an array?

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!

How do you change a value in an array map?

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.

How do you map an array of objects?

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.


1 Answers

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!

like image 100
pimlottc Avatar answered Sep 28 '22 09:09

pimlottc