Reputation: 6481
Consider this code:
const map1 = Immutable.Map({a:1, b:2, c:3});
const myMap = map1.map((elem, index) => {
return "Hello " + elem;
})
console.log(myMap.toJS());
// prnts {a: "Hello 1", b: "Hello 2", c: "Hello 3"}
I want the output as ['Hello1', 'Hello2, 'Hello3']
, but map
is giving me an object with the keys also. Why am I not getting an array as output like a normal JavaScript map
works? And what is the best way to achieve the desired result? (I can use forEach
instead of map
, and push the result of each iteration in an array, but I am looking for a better method).
Upvotes: 2
Views: 1161
Reputation: 665
Just providing a different flavor using reduce
const map1 = Immutable.Map({a:1, b:2, c:3});
const myMap = map1.reduce((accumulator, value) => {
accumulator.push("Hello" + value);
return accumulator;
}, [])
console.log(myMap);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>
Upvotes: 0
Reputation: 12373
You can get the array by simply using myMap.keys
Array.from(myMap.keys());
Runnable code snippet for the same is as under:
const map1 = Immutable.Map({a:1, b:2, c:3});
const myMap = map1.map((elem, index) => {
return "Hello " + elem;
})
console.log(Array.from(myMap.keys()));
Upvotes: 0
Reputation: 467
Use toArray() instead toJS():
const map1 = Immutable.Map({a:1, b:2, c:3});
const myMap = map1.map((elem, index) => {
return "Hello " + elem;
})
console.log(myMap.toArray());
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>
Upvotes: 1