Using a map function on a 'Map' to change valuesTransforming a Javascript iterator into an arrayUsing map/filter behavior on Map instanceHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesvar functionName = function() vs function functionName() How do I sort a dictionary by value?How do I loop through or enumerate a JavaScript object?How do you check if a variable is an array in JavaScript?$(document).ready equivalent without jQueryWhere can I find documentation on formatting a date in JavaScript?Convert form data to JavaScript object with jQueryHow to decide when to use Node.js?

What property of a BJT transistor makes it an amplifier?

I have a unique character that I'm having a problem writing. He's a virus!

Why wasn't the Night King naked in S08E03?

How can I close a gap between my fence and my neighbor's that's on his side of the property line?

Why is B♯ higher than C♭ in 31-ET?

Send iMessage from Firefox

Would glacier 'trees' be plausible?

As matter approaches a black hole, does it speed up?

Why didn't the check-in agent recognize my long term visa?

Building a list of products from the elements in another list

What happens if you dump antimatter into a black hole?

How long would it take for people to notice a mass disappearance?

What is the closest airport to the center of the city it serves?

What is the difference between 反日 and 日本たたき?

Purpose of のは in this sentence?

Randomness of Python's random

Why doesn't WotC use established keywords on all new cards?

Did we get closer to another plane than we were supposed to, or was the pilot just protecting our delicate sensibilities?

Can Infinity Stones be retrieved more than once?

Can a nothic's Weird Insight action discover secrets about a player character that the character doesn't know about themselves?

Why do only some White Walkers shatter into ice chips?

Getting a W on your transcript for grad school applications

Independent, post-Brexit Scotland - would there be a hard border with England?

Manager is threatening to grade me poorly if I don't complete the project



Using a map function on a 'Map' to change values


Transforming a Javascript iterator into an arrayUsing map/filter behavior on Map instanceHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesvar functionName = function() vs function functionName() How do I sort a dictionary by value?How do I loop through or enumerate a JavaScript object?How do you check if a variable is an array in JavaScript?$(document).ready equivalent without jQueryWhere can I find documentation on formatting a date in JavaScript?Convert form data to JavaScript object with jQueryHow to decide when to use Node.js?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








11















I can use a Map and then set values:



const a = new Map([["a", "b"], ["c", "d"]])


Now if I want to apply a function to all values in a functional way (without for ... of or .forEach), I thought I could have done something like this:



const b = a.map(([k, v]) => [k, doSomethingWith(v)]);


But there is no map function on a Map. Is there a built-in/elegant way to map a Map?










share|improve this question
























  • Use Map#entries then .map on them a.entries().map(...)

    – ponury-kostek
    Apr 24 at 9:02











  • @ponury-kostek It won't work because Map.entries() return an Iterator (not Array); and Iterators haven't .map method...

    – FZs
    Apr 24 at 9:10











  • Unfortunately, there is no elegant way. You have to process the entries and then produce a new Map out of the result.

    – VLAZ
    Apr 24 at 9:11











  • Possible duplicate of Using map/filter behavior on Map instance

    – Bergi
    Apr 24 at 13:57

















11















I can use a Map and then set values:



const a = new Map([["a", "b"], ["c", "d"]])


Now if I want to apply a function to all values in a functional way (without for ... of or .forEach), I thought I could have done something like this:



const b = a.map(([k, v]) => [k, doSomethingWith(v)]);


But there is no map function on a Map. Is there a built-in/elegant way to map a Map?










share|improve this question
























  • Use Map#entries then .map on them a.entries().map(...)

    – ponury-kostek
    Apr 24 at 9:02











  • @ponury-kostek It won't work because Map.entries() return an Iterator (not Array); and Iterators haven't .map method...

    – FZs
    Apr 24 at 9:10











  • Unfortunately, there is no elegant way. You have to process the entries and then produce a new Map out of the result.

    – VLAZ
    Apr 24 at 9:11











  • Possible duplicate of Using map/filter behavior on Map instance

    – Bergi
    Apr 24 at 13:57













11












11








11








I can use a Map and then set values:



const a = new Map([["a", "b"], ["c", "d"]])


Now if I want to apply a function to all values in a functional way (without for ... of or .forEach), I thought I could have done something like this:



const b = a.map(([k, v]) => [k, doSomethingWith(v)]);


But there is no map function on a Map. Is there a built-in/elegant way to map a Map?










share|improve this question
















I can use a Map and then set values:



const a = new Map([["a", "b"], ["c", "d"]])


Now if I want to apply a function to all values in a functional way (without for ... of or .forEach), I thought I could have done something like this:



const b = a.map(([k, v]) => [k, doSomethingWith(v)]);


But there is no map function on a Map. Is there a built-in/elegant way to map a Map?







javascript dictionary ecmascript-6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 24 at 10:26









Peter Mortensen

14k1987114




14k1987114










asked Apr 24 at 8:56









rap-2-hrap-2-h

10.4k1176141




10.4k1176141












  • Use Map#entries then .map on them a.entries().map(...)

    – ponury-kostek
    Apr 24 at 9:02











  • @ponury-kostek It won't work because Map.entries() return an Iterator (not Array); and Iterators haven't .map method...

    – FZs
    Apr 24 at 9:10











  • Unfortunately, there is no elegant way. You have to process the entries and then produce a new Map out of the result.

    – VLAZ
    Apr 24 at 9:11











  • Possible duplicate of Using map/filter behavior on Map instance

    – Bergi
    Apr 24 at 13:57

















  • Use Map#entries then .map on them a.entries().map(...)

    – ponury-kostek
    Apr 24 at 9:02











  • @ponury-kostek It won't work because Map.entries() return an Iterator (not Array); and Iterators haven't .map method...

    – FZs
    Apr 24 at 9:10











  • Unfortunately, there is no elegant way. You have to process the entries and then produce a new Map out of the result.

    – VLAZ
    Apr 24 at 9:11











  • Possible duplicate of Using map/filter behavior on Map instance

    – Bergi
    Apr 24 at 13:57
















Use Map#entries then .map on them a.entries().map(...)

– ponury-kostek
Apr 24 at 9:02





Use Map#entries then .map on them a.entries().map(...)

– ponury-kostek
Apr 24 at 9:02













@ponury-kostek It won't work because Map.entries() return an Iterator (not Array); and Iterators haven't .map method...

– FZs
Apr 24 at 9:10





@ponury-kostek It won't work because Map.entries() return an Iterator (not Array); and Iterators haven't .map method...

– FZs
Apr 24 at 9:10













Unfortunately, there is no elegant way. You have to process the entries and then produce a new Map out of the result.

– VLAZ
Apr 24 at 9:11





Unfortunately, there is no elegant way. You have to process the entries and then produce a new Map out of the result.

– VLAZ
Apr 24 at 9:11













Possible duplicate of Using map/filter behavior on Map instance

– Bergi
Apr 24 at 13:57





Possible duplicate of Using map/filter behavior on Map instance

– Bergi
Apr 24 at 13:57












5 Answers
5






active

oldest

votes


















12














You could use Array.from for getting entries and mapping new values and take this result for a new Map.



const b = new Map(Array.from(
a,
([k, v]) => [k, doSomethingWith(v)]
));





share|improve this answer






























    4














    The most elegant/concise way I am aware of is by converting the map to an array with the spread operator (...), applying .map to that array and then creating a Map from it again:



    const a = new Map([["a", "b"], ["c", "d"]])
    const b = new Map([...a].map(([k,v])=>[k, v.toUpperCase()]))
    // b: Map(2) "a" => "B", "c" => "D"





    share|improve this answer
































      2














      There are no builtin methods for this (yet!). The most elegant way currently is to use generators:



      const b = new Map((function*() 
      for (const [k, v] of a)
      yield [k, doSomethingWith(v)];
      )());


      I would however recommend to write helper functions for this that work with arbitrary iterables:



      function* mapValue(iterable, callback) 
      for (const [k, v] of a)
      yield [k, callback(v)];

      const b = new Map(mapValue(a, doSomethingWith));





      share|improve this answer






























        0














        You could use Symbol.iterator for changing or creating a new Map.






        function f (iterator) 
        for (let item of iterator1)
        item[0] = 1;
        item[1] = 'hello world';
        console.log(item);



        var map1 = new Map();
        map1.set('0', 'foo');
        map1.set(1, 'bar');
        var iterator1 = map1[Symbol.iterator]();

        f(iterator1);








        share|improve this answer


















        • 1





          for (let item of iterator1) that should be iterator, no?

          – VLAZ
          Apr 24 at 9:13












        • And the question was: 'in a functional way (without for ... of or .forEach)'. This example uses for...of

          – FZs
          Apr 24 at 9:15


















        0














        You could do that like this:



        let b = new Map(a)
        b.forEach((value,key,myMap) => myMap.set(key, dosomething(value)))


        or:



        let b
        (b = new Map(a)).forEach((value,key,myMap) => myMap.set(key, dosomething(value)))





        share|improve this answer

























          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55826132%2fusing-a-map-function-on-a-map-to-change-values%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          12














          You could use Array.from for getting entries and mapping new values and take this result for a new Map.



          const b = new Map(Array.from(
          a,
          ([k, v]) => [k, doSomethingWith(v)]
          ));





          share|improve this answer



























            12














            You could use Array.from for getting entries and mapping new values and take this result for a new Map.



            const b = new Map(Array.from(
            a,
            ([k, v]) => [k, doSomethingWith(v)]
            ));





            share|improve this answer

























              12












              12








              12







              You could use Array.from for getting entries and mapping new values and take this result for a new Map.



              const b = new Map(Array.from(
              a,
              ([k, v]) => [k, doSomethingWith(v)]
              ));





              share|improve this answer













              You could use Array.from for getting entries and mapping new values and take this result for a new Map.



              const b = new Map(Array.from(
              a,
              ([k, v]) => [k, doSomethingWith(v)]
              ));






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Apr 24 at 9:04









              Nina ScholzNina Scholz

              202k16115184




              202k16115184























                  4














                  The most elegant/concise way I am aware of is by converting the map to an array with the spread operator (...), applying .map to that array and then creating a Map from it again:



                  const a = new Map([["a", "b"], ["c", "d"]])
                  const b = new Map([...a].map(([k,v])=>[k, v.toUpperCase()]))
                  // b: Map(2) "a" => "B", "c" => "D"





                  share|improve this answer





























                    4














                    The most elegant/concise way I am aware of is by converting the map to an array with the spread operator (...), applying .map to that array and then creating a Map from it again:



                    const a = new Map([["a", "b"], ["c", "d"]])
                    const b = new Map([...a].map(([k,v])=>[k, v.toUpperCase()]))
                    // b: Map(2) "a" => "B", "c" => "D"





                    share|improve this answer



























                      4












                      4








                      4







                      The most elegant/concise way I am aware of is by converting the map to an array with the spread operator (...), applying .map to that array and then creating a Map from it again:



                      const a = new Map([["a", "b"], ["c", "d"]])
                      const b = new Map([...a].map(([k,v])=>[k, v.toUpperCase()]))
                      // b: Map(2) "a" => "B", "c" => "D"





                      share|improve this answer















                      The most elegant/concise way I am aware of is by converting the map to an array with the spread operator (...), applying .map to that array and then creating a Map from it again:



                      const a = new Map([["a", "b"], ["c", "d"]])
                      const b = new Map([...a].map(([k,v])=>[k, v.toUpperCase()]))
                      // b: Map(2) "a" => "B", "c" => "D"






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Apr 24 at 10:20

























                      answered Apr 24 at 10:14









                      nitzelnitzel

                      31127




                      31127





















                          2














                          There are no builtin methods for this (yet!). The most elegant way currently is to use generators:



                          const b = new Map((function*() 
                          for (const [k, v] of a)
                          yield [k, doSomethingWith(v)];
                          )());


                          I would however recommend to write helper functions for this that work with arbitrary iterables:



                          function* mapValue(iterable, callback) 
                          for (const [k, v] of a)
                          yield [k, callback(v)];

                          const b = new Map(mapValue(a, doSomethingWith));





                          share|improve this answer



























                            2














                            There are no builtin methods for this (yet!). The most elegant way currently is to use generators:



                            const b = new Map((function*() 
                            for (const [k, v] of a)
                            yield [k, doSomethingWith(v)];
                            )());


                            I would however recommend to write helper functions for this that work with arbitrary iterables:



                            function* mapValue(iterable, callback) 
                            for (const [k, v] of a)
                            yield [k, callback(v)];

                            const b = new Map(mapValue(a, doSomethingWith));





                            share|improve this answer

























                              2












                              2








                              2







                              There are no builtin methods for this (yet!). The most elegant way currently is to use generators:



                              const b = new Map((function*() 
                              for (const [k, v] of a)
                              yield [k, doSomethingWith(v)];
                              )());


                              I would however recommend to write helper functions for this that work with arbitrary iterables:



                              function* mapValue(iterable, callback) 
                              for (const [k, v] of a)
                              yield [k, callback(v)];

                              const b = new Map(mapValue(a, doSomethingWith));





                              share|improve this answer













                              There are no builtin methods for this (yet!). The most elegant way currently is to use generators:



                              const b = new Map((function*() 
                              for (const [k, v] of a)
                              yield [k, doSomethingWith(v)];
                              )());


                              I would however recommend to write helper functions for this that work with arbitrary iterables:



                              function* mapValue(iterable, callback) 
                              for (const [k, v] of a)
                              yield [k, callback(v)];

                              const b = new Map(mapValue(a, doSomethingWith));






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Apr 24 at 14:10









                              BergiBergi

                              385k64596926




                              385k64596926





















                                  0














                                  You could use Symbol.iterator for changing or creating a new Map.






                                  function f (iterator) 
                                  for (let item of iterator1)
                                  item[0] = 1;
                                  item[1] = 'hello world';
                                  console.log(item);



                                  var map1 = new Map();
                                  map1.set('0', 'foo');
                                  map1.set(1, 'bar');
                                  var iterator1 = map1[Symbol.iterator]();

                                  f(iterator1);








                                  share|improve this answer


















                                  • 1





                                    for (let item of iterator1) that should be iterator, no?

                                    – VLAZ
                                    Apr 24 at 9:13












                                  • And the question was: 'in a functional way (without for ... of or .forEach)'. This example uses for...of

                                    – FZs
                                    Apr 24 at 9:15















                                  0














                                  You could use Symbol.iterator for changing or creating a new Map.






                                  function f (iterator) 
                                  for (let item of iterator1)
                                  item[0] = 1;
                                  item[1] = 'hello world';
                                  console.log(item);



                                  var map1 = new Map();
                                  map1.set('0', 'foo');
                                  map1.set(1, 'bar');
                                  var iterator1 = map1[Symbol.iterator]();

                                  f(iterator1);








                                  share|improve this answer


















                                  • 1





                                    for (let item of iterator1) that should be iterator, no?

                                    – VLAZ
                                    Apr 24 at 9:13












                                  • And the question was: 'in a functional way (without for ... of or .forEach)'. This example uses for...of

                                    – FZs
                                    Apr 24 at 9:15













                                  0












                                  0








                                  0







                                  You could use Symbol.iterator for changing or creating a new Map.






                                  function f (iterator) 
                                  for (let item of iterator1)
                                  item[0] = 1;
                                  item[1] = 'hello world';
                                  console.log(item);



                                  var map1 = new Map();
                                  map1.set('0', 'foo');
                                  map1.set(1, 'bar');
                                  var iterator1 = map1[Symbol.iterator]();

                                  f(iterator1);








                                  share|improve this answer













                                  You could use Symbol.iterator for changing or creating a new Map.






                                  function f (iterator) 
                                  for (let item of iterator1)
                                  item[0] = 1;
                                  item[1] = 'hello world';
                                  console.log(item);



                                  var map1 = new Map();
                                  map1.set('0', 'foo');
                                  map1.set(1, 'bar');
                                  var iterator1 = map1[Symbol.iterator]();

                                  f(iterator1);








                                  function f (iterator) 
                                  for (let item of iterator1)
                                  item[0] = 1;
                                  item[1] = 'hello world';
                                  console.log(item);



                                  var map1 = new Map();
                                  map1.set('0', 'foo');
                                  map1.set(1, 'bar');
                                  var iterator1 = map1[Symbol.iterator]();

                                  f(iterator1);





                                  function f (iterator) 
                                  for (let item of iterator1)
                                  item[0] = 1;
                                  item[1] = 'hello world';
                                  console.log(item);



                                  var map1 = new Map();
                                  map1.set('0', 'foo');
                                  map1.set(1, 'bar');
                                  var iterator1 = map1[Symbol.iterator]();

                                  f(iterator1);






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Apr 24 at 9:12









                                  koλzarkoλzar

                                  5761518




                                  5761518







                                  • 1





                                    for (let item of iterator1) that should be iterator, no?

                                    – VLAZ
                                    Apr 24 at 9:13












                                  • And the question was: 'in a functional way (without for ... of or .forEach)'. This example uses for...of

                                    – FZs
                                    Apr 24 at 9:15












                                  • 1





                                    for (let item of iterator1) that should be iterator, no?

                                    – VLAZ
                                    Apr 24 at 9:13












                                  • And the question was: 'in a functional way (without for ... of or .forEach)'. This example uses for...of

                                    – FZs
                                    Apr 24 at 9:15







                                  1




                                  1





                                  for (let item of iterator1) that should be iterator, no?

                                  – VLAZ
                                  Apr 24 at 9:13






                                  for (let item of iterator1) that should be iterator, no?

                                  – VLAZ
                                  Apr 24 at 9:13














                                  And the question was: 'in a functional way (without for ... of or .forEach)'. This example uses for...of

                                  – FZs
                                  Apr 24 at 9:15





                                  And the question was: 'in a functional way (without for ... of or .forEach)'. This example uses for...of

                                  – FZs
                                  Apr 24 at 9:15











                                  0














                                  You could do that like this:



                                  let b = new Map(a)
                                  b.forEach((value,key,myMap) => myMap.set(key, dosomething(value)))


                                  or:



                                  let b
                                  (b = new Map(a)).forEach((value,key,myMap) => myMap.set(key, dosomething(value)))





                                  share|improve this answer





























                                    0














                                    You could do that like this:



                                    let b = new Map(a)
                                    b.forEach((value,key,myMap) => myMap.set(key, dosomething(value)))


                                    or:



                                    let b
                                    (b = new Map(a)).forEach((value,key,myMap) => myMap.set(key, dosomething(value)))





                                    share|improve this answer



























                                      0












                                      0








                                      0







                                      You could do that like this:



                                      let b = new Map(a)
                                      b.forEach((value,key,myMap) => myMap.set(key, dosomething(value)))


                                      or:



                                      let b
                                      (b = new Map(a)).forEach((value,key,myMap) => myMap.set(key, dosomething(value)))





                                      share|improve this answer















                                      You could do that like this:



                                      let b = new Map(a)
                                      b.forEach((value,key,myMap) => myMap.set(key, dosomething(value)))


                                      or:



                                      let b
                                      (b = new Map(a)).forEach((value,key,myMap) => myMap.set(key, dosomething(value)))






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Apr 24 at 9:35

























                                      answered Apr 24 at 9:26









                                      欧阳维杰欧阳维杰

                                      431512




                                      431512



























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55826132%2fusing-a-map-function-on-a-map-to-change-values%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

                                          Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

                                          What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company