Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 751
rublex Avatar asked May 13 '15 04:05

rublex


People also ask

Can javascript map have object as key?

Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, value pair in the same order as inserted.

How do you add a map key?

Use the set() method to add a key/value pair to a Map , e.g. map. set('myKey', 'myValue') . The set() method adds or updates the element with the provided key and value and returns the Map object.

What is the use of map () in Javascript?

map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.

Can we use break inside map?

Not possible, We can't break #array. map, it will run for each element of array.


2 Answers

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;
});
like image 66
Lim H. Avatar answered Sep 21 '22 17:09

Lim H.


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

like image 28
Grzegorz Kubiszyn Avatar answered Sep 22 '22 17:09

Grzegorz Kubiszyn