Set key dynamically inside map () in javascript?

So, I know how to dynamically set a key as follows:

var hashObj = {}; hashObj[someValue] = otherValue; 

But I did not see the answer to map() :

 var list = ['a', 'b', 'c']; var hashObject = list.map(function(someValue) { return { someValue: 'blah' }; }); // should return: [ {'a': 'blah'}, {'b': 'blah'}, {'c': 'blah'} ]; 

I know that I can do this in a for loop and so, but this is not possible in javascript using only map() ?

+5
source share
2 answers

You need to get someValue to evaluate how its value is. If you use object notation, it will be interpreted literally as a string.

You can use a temporary object to achieve the desired result:

 var list = ['a', 'b', 'c']; var hashObject = list.map(function(someValue) { var tmp = {}; tmp[someValue] = 'blah'; return tmp; }); 
+4
source

Typically, the map () method is used to get a new array from each return value. In your case, I recommend using forEach ().

 var list = ['a','b','c']; var hashObject = {}; list.forEach( function( key ) { hashObject[ key ] = 'blah'; }); 

Or use the underscore.js library object ()

 var list = ['a','b','c']; var hashObject = _.object( list ); // { a: undefined, b: undefined, c: undefined } hashObject = _.mapObject( hashObject, function( val, key ) { return 'blah'; }); 

Then again, Array.prototype.map is used only to get a new "array", not an "object".

0
source

All Articles