views:

32

answers:

2

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

+1  A: 
patrick dw
Wouldn't this result in an endless loop?
Nick Craver
If `each` works on a copy no. I tested it and it works.
Alin Purcaru
@Nick - It doesn't in Safari, but good point. I guess I'll give it a test in IE.
patrick dw
Will this modify the original array?
Adam
@Adam - Yes. It is adding new keys/values, and deleting the old one. Did you want to keep the original?
patrick dw
@patrick - It locks up IE with an out of memory exception here. @Alin - test things like this in all browsers, don't assume...also it does *not* operate on a copy.
Nick Craver
@Nick - Indeed I should have tested first. Especially since the [spec](http://bclary.com/2004/11/07/#a-12.6.4) seems to leave open the possibility of enumeration of properties added during a `for/in`. *"If new properties are added to the object being enumerated during enumeration, the newly added properties are not guaranteed to be visited in the active enumeration."* I wonder why it isn't required to be one way or the other. Seems that both IE and Safari are in compliance.
patrick dw
@patrick - I think it's because order of enumeration isn't guaranteed, it actually causes some issues elsewhere too, let me see if I can find the question this came up on a while back. *Edit:* Here it is, same root issue: http://stackoverflow.com/questions/3399649/isplainobject-true-in-ie
Nick Craver
@Nick - Well that would make sense. I remember that question when it came up. Thanks for the link (and reminder). :o)
patrick dw
+3  A: 

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.

Nick Craver