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' };
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!
Something like this would 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'd call it like this:
classes = prependObj(classes, "a-");
You can test it here. This does not modify the original object and doesn't have any jQuery dependency, so you can use it with or without.
If you wanted to use jQuery to take care of the loop, you could use $.each()
.
You can't really modify the existing key, but you can replace the key/value pair with a new set that has the new key and the 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 wanted to keep the original, or if there's an issue in some browsers with an infinite loop (I'm testing...) do this:
Don't forget that javascript has closures:
var classes = { red: 'Red', green: 'Green' };
var prefixedClasses = {}
$.map(classes, function(v, k) {
prefixedClasses['a-' + k] = v;
});
should do it.
精彩评论