12

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()?

3 Answers 3

16

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, you cannot create a JS literal object definition that uses a variable name for a property name. As such, you must declare an object and then assign the property (using the property name in variable) separately as this answer does.
ES6 Shorthand: return { [someValue]: 'blah' }
5

I know it is really old question, but answer can be helpful for others.

As it has been already said, Array.prototype.map is used to get new array.

But if you want to get object instead of array - maybe you should think about using Array.prototype.reduce (https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)?

const list = ['a', 'b', 'c'];

const hashObject = list.reduce((acc, current) => {
  acc[current] = 'blah';
  return acc;
}, {});

// hashObject equals: {"a":"blah","b":"blah","c":"blah"}

And if you want achieve the same result as mentioned in your question, you can use Array.prototype.map of course:

const list = ['a', 'b', 'c'];

const hashArrayOfObjects = list.map((current) => {
  return {[current]: 'blah'};
});

// hashArrayOfObjects equals: [{"a":"blah"},{"b":"blah"},{"c":"blah"}]

You can check how it works on CodePen: https://codepen.io/grygork/pen/PojNrXO

Comments

0

Commonly the 'map()' method is used to get new array from each return value. In your case, I recommend to use forEach().

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

Or use object() of underscore.js library

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 only used to get new 'array' not 'object'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.