Change an object using jQuery.map?

I have a key-value pair like

var classes = { red: 'Red', green: 'Green' };

How can I add each of the keys with a specific value? Can this be done using jQuery.map?

The end result I'm looking for is

classes = { 'a-red': 'Red', 'a-green': 'Green' };

+4
source share
4 answers

Something like this will work:

 function prependObj(obj, prefix) { var result = {}; for(var i in obj) if(obj.hasOwnProperty(i)) result[prefix+i] = obj[i]; return result; } 

Then you would call it like this:

 classes = prependObj(classes, "a-"); 

Here you can test it . This does not modify the original object and has no jQuery dependency, so you can use it with or without.

+5
source

These answers will work, but they are not as 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 stages: firstly, the card works with key-value pairs of the source object and returns a list of unique objects. Secondly, $. Extend function combines them all together into one object; . The apply method is used to pass arguments to the function as an array.

Unfortunately, the lack of a good way to create object literals with variable key names makes it so ugly, and it may not be as efficient, but it is a great single-line layer!

+9
source

If you want to use jQuery to execute a loop, you can use $.each() .

You cannot change an existing key, but you can replace a key / value pair with a new set with a new key and old value and delete the old set.

 var classes = { red: 'Red', green: 'Green' }; var newClasses = {}; $.each( classes, function( key,val ) { newClasses["a-" + key] = val; }); 

Or with a regular for loop:

 var classes = { red: 'Red', green: 'Green' }; var newClasses = {}; for( var name in classes ) { if( classes.hasOwnProperty( name ) ) newClasses["a-" + key] = classes[name]; }); 

 var classes = { red: 'Red', green: 'Green' }; $.each( classes, function( key,val ) { classes["a-" + key] = val; delete classes[key]; }); 

EDIT: If you want to keep the original, or if some browsers have a problem with an infinite loop (I'm testing ...), follow these steps: C>

+3
source

Don't forget javascript has closures:

 var classes = { red: 'Red', green: 'Green' }; var prefixedClasses = {} $.map(classes, function(v, k) { prefixedClasses['a-' + k] = v; }); 

must do it.

0
source

All Articles