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()
?
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.
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.
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.
Not possible, We can't break #array. map, it will run for each element of array.
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;
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With