Search code examples
javascriptreactjsimmutabilityimmutable.js

Concat values of an immutable map in javascript


i'm having an immutable map like this: pinMap = Map({pin1: 1}, {pin2: 2}, {pin3: 3}, {pin4: 4}). Now i want to create an objct as follows: obj = {pinCode: 1234} whose value is the merged values of the map. I've tried the following command: const obj = {obj: {...pinMap.values()} } with no success. Do you have any idea on how to achieve this?


Solution

  • Assuming your map was created as string: number pairs,

      let pinMap = new Map();
      pinMap.set("pin1", 1); //Assuming these are numbers
      pinMap.set("pin2", 2);
      pinMap.set("pin3", 3);
      pinMap.set("pin4", 4);
    

    Map has a couple of ways to iterate over the map. For ease, we can use the forEach iteration method

      let pinCode = "";
      pinMap.forEach((value) => {
        pinCode = pinCode + value.toString();
      });
    
      let result = {
        pinCode: pinCode
      };