Search code examples
javascriptarraysassociative-array

Set key dynamically inside map() in javascript?


So I know how to set the key dynamically like this:

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

But I haven't seen any answer regarding 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 I can do this in a for loop and such, but is this not possible in javascript using just map()?


Solution

  • You need to get someValue to be evaluated as its value. If you use object notation, it will be interpreted literally as string.

    You can use a temporary object to achieve what you want:

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