How do I return the object I want by using a key in a forEach loop?










2















Consider this code:



const year = 1910;

const items = [

name: 'gallon of gas',
year: 1910,
price: .12
,

name: 'gallon of gas',
year: 1960,
price: .30
,

name: 'gallon of gas',
year: 2010,
price: 2.80

]


How do I display the price of the object corresponding to the year defined above?



items.forEach(d => 
if (d.year === year)
return d.price;

);


^ Why doesn't that solution work?










share|improve this question
























  • forEach() doesn't return a value. Use find() instead.

    – Robby Cornelissen
    Nov 15 '18 at 1:32












  • It sounds like you are trying to only return the prices? So if that is the case, You should look up the map(fn) utility. Example: items.map( item => item.price);

    – Fallenreaper
    Nov 15 '18 at 1:34






  • 1





    '1910' === 1910 would return false

    – Liutong Chen
    Nov 15 '18 at 1:36












  • sorry, edited the post to make it a number.

    – InspectorDanno
    Nov 15 '18 at 1:36















2















Consider this code:



const year = 1910;

const items = [

name: 'gallon of gas',
year: 1910,
price: .12
,

name: 'gallon of gas',
year: 1960,
price: .30
,

name: 'gallon of gas',
year: 2010,
price: 2.80

]


How do I display the price of the object corresponding to the year defined above?



items.forEach(d => 
if (d.year === year)
return d.price;

);


^ Why doesn't that solution work?










share|improve this question
























  • forEach() doesn't return a value. Use find() instead.

    – Robby Cornelissen
    Nov 15 '18 at 1:32












  • It sounds like you are trying to only return the prices? So if that is the case, You should look up the map(fn) utility. Example: items.map( item => item.price);

    – Fallenreaper
    Nov 15 '18 at 1:34






  • 1





    '1910' === 1910 would return false

    – Liutong Chen
    Nov 15 '18 at 1:36












  • sorry, edited the post to make it a number.

    – InspectorDanno
    Nov 15 '18 at 1:36













2












2








2


1






Consider this code:



const year = 1910;

const items = [

name: 'gallon of gas',
year: 1910,
price: .12
,

name: 'gallon of gas',
year: 1960,
price: .30
,

name: 'gallon of gas',
year: 2010,
price: 2.80

]


How do I display the price of the object corresponding to the year defined above?



items.forEach(d => 
if (d.year === year)
return d.price;

);


^ Why doesn't that solution work?










share|improve this question
















Consider this code:



const year = 1910;

const items = [

name: 'gallon of gas',
year: 1910,
price: .12
,

name: 'gallon of gas',
year: 1960,
price: .30
,

name: 'gallon of gas',
year: 2010,
price: 2.80

]


How do I display the price of the object corresponding to the year defined above?



items.forEach(d => 
if (d.year === year)
return d.price;

);


^ Why doesn't that solution work?







javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 1:35







InspectorDanno

















asked Nov 15 '18 at 1:30









InspectorDannoInspectorDanno

908




908












  • forEach() doesn't return a value. Use find() instead.

    – Robby Cornelissen
    Nov 15 '18 at 1:32












  • It sounds like you are trying to only return the prices? So if that is the case, You should look up the map(fn) utility. Example: items.map( item => item.price);

    – Fallenreaper
    Nov 15 '18 at 1:34






  • 1





    '1910' === 1910 would return false

    – Liutong Chen
    Nov 15 '18 at 1:36












  • sorry, edited the post to make it a number.

    – InspectorDanno
    Nov 15 '18 at 1:36

















  • forEach() doesn't return a value. Use find() instead.

    – Robby Cornelissen
    Nov 15 '18 at 1:32












  • It sounds like you are trying to only return the prices? So if that is the case, You should look up the map(fn) utility. Example: items.map( item => item.price);

    – Fallenreaper
    Nov 15 '18 at 1:34






  • 1





    '1910' === 1910 would return false

    – Liutong Chen
    Nov 15 '18 at 1:36












  • sorry, edited the post to make it a number.

    – InspectorDanno
    Nov 15 '18 at 1:36
















forEach() doesn't return a value. Use find() instead.

– Robby Cornelissen
Nov 15 '18 at 1:32






forEach() doesn't return a value. Use find() instead.

– Robby Cornelissen
Nov 15 '18 at 1:32














It sounds like you are trying to only return the prices? So if that is the case, You should look up the map(fn) utility. Example: items.map( item => item.price);

– Fallenreaper
Nov 15 '18 at 1:34





It sounds like you are trying to only return the prices? So if that is the case, You should look up the map(fn) utility. Example: items.map( item => item.price);

– Fallenreaper
Nov 15 '18 at 1:34




1




1





'1910' === 1910 would return false

– Liutong Chen
Nov 15 '18 at 1:36






'1910' === 1910 would return false

– Liutong Chen
Nov 15 '18 at 1:36














sorry, edited the post to make it a number.

– InspectorDanno
Nov 15 '18 at 1:36





sorry, edited the post to make it a number.

– InspectorDanno
Nov 15 '18 at 1:36












3 Answers
3






active

oldest

votes


















2














The forEach() function doesn't return a value, regardless of what you return in the callback function. Use find() instead to find the item that matches your criteria:






const year = '1910';

const items = [

name: 'gallon of gas',
year: 1910,
price: .12
,

name: 'gallon of gas',
year: 1960,
price: .30
,

name: 'gallon of gas',
year: 2010,
price: 2.80

];

const item = items.find(i => i.year == year);

console.log(item.price);





Note: you can't use strict comparison (===) in the callback to find() because you're comparing a year string to a year number. Probably a good idea to address that.






share|improve this answer






























    1














    Because that return statement is inside of the handler of the function forEach, basically, you're returning the handler execution and not the main function.



    What you need to do is either to use a for-loop or the function find as follow:



    let found = items.find(d => d.year === year);
    if (found) return found.price;


    Or a vanilla for-loop:



    for (let i = 0; i < items.length; i++) 
    if (items[i].year === year) return items[i].price;





    share|improve this answer






























      -2














      This needs ES6 (babel). Hope this helps! Got it from https://zellwk.com/blog/looping-through-js-objects/.






      const year = 1910;

      const items = [

      name: 'gallon of gas',
      year: 1910,
      price: .12
      ,

      name: 'gallon of gas',
      year: 1960,
      price: .30
      ,

      name: 'gallon of gas',
      year: 2010,
      price: 2.80

      ]
      const values = Object.values(items)
      for (const value of values)
      //you can't return, but you can use the value or store it in a variable/array
      console.log(value.price);








      share|improve this answer























      • 1) Calling Object.values() on an array will just return the array, so you can get rid of that and don't need ES6. 2) Your solution prints out the prices (same as just doing items.forEach(i => console.log(i.price))), it doesn't perform a lookup based on the year as was asked in the question.

        – Robby Cornelissen
        Nov 15 '18 at 1:48










      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%2f53311197%2fhow-do-i-return-the-object-i-want-by-using-a-key-in-a-foreach-loop%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      The forEach() function doesn't return a value, regardless of what you return in the callback function. Use find() instead to find the item that matches your criteria:






      const year = '1910';

      const items = [

      name: 'gallon of gas',
      year: 1910,
      price: .12
      ,

      name: 'gallon of gas',
      year: 1960,
      price: .30
      ,

      name: 'gallon of gas',
      year: 2010,
      price: 2.80

      ];

      const item = items.find(i => i.year == year);

      console.log(item.price);





      Note: you can't use strict comparison (===) in the callback to find() because you're comparing a year string to a year number. Probably a good idea to address that.






      share|improve this answer



























        2














        The forEach() function doesn't return a value, regardless of what you return in the callback function. Use find() instead to find the item that matches your criteria:






        const year = '1910';

        const items = [

        name: 'gallon of gas',
        year: 1910,
        price: .12
        ,

        name: 'gallon of gas',
        year: 1960,
        price: .30
        ,

        name: 'gallon of gas',
        year: 2010,
        price: 2.80

        ];

        const item = items.find(i => i.year == year);

        console.log(item.price);





        Note: you can't use strict comparison (===) in the callback to find() because you're comparing a year string to a year number. Probably a good idea to address that.






        share|improve this answer

























          2












          2








          2







          The forEach() function doesn't return a value, regardless of what you return in the callback function. Use find() instead to find the item that matches your criteria:






          const year = '1910';

          const items = [

          name: 'gallon of gas',
          year: 1910,
          price: .12
          ,

          name: 'gallon of gas',
          year: 1960,
          price: .30
          ,

          name: 'gallon of gas',
          year: 2010,
          price: 2.80

          ];

          const item = items.find(i => i.year == year);

          console.log(item.price);





          Note: you can't use strict comparison (===) in the callback to find() because you're comparing a year string to a year number. Probably a good idea to address that.






          share|improve this answer













          The forEach() function doesn't return a value, regardless of what you return in the callback function. Use find() instead to find the item that matches your criteria:






          const year = '1910';

          const items = [

          name: 'gallon of gas',
          year: 1910,
          price: .12
          ,

          name: 'gallon of gas',
          year: 1960,
          price: .30
          ,

          name: 'gallon of gas',
          year: 2010,
          price: 2.80

          ];

          const item = items.find(i => i.year == year);

          console.log(item.price);





          Note: you can't use strict comparison (===) in the callback to find() because you're comparing a year string to a year number. Probably a good idea to address that.






          const year = '1910';

          const items = [

          name: 'gallon of gas',
          year: 1910,
          price: .12
          ,

          name: 'gallon of gas',
          year: 1960,
          price: .30
          ,

          name: 'gallon of gas',
          year: 2010,
          price: 2.80

          ];

          const item = items.find(i => i.year == year);

          console.log(item.price);





          const year = '1910';

          const items = [

          name: 'gallon of gas',
          year: 1910,
          price: .12
          ,

          name: 'gallon of gas',
          year: 1960,
          price: .30
          ,

          name: 'gallon of gas',
          year: 2010,
          price: 2.80

          ];

          const item = items.find(i => i.year == year);

          console.log(item.price);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 15 '18 at 1:34









          Robby CornelissenRobby Cornelissen

          45k137091




          45k137091























              1














              Because that return statement is inside of the handler of the function forEach, basically, you're returning the handler execution and not the main function.



              What you need to do is either to use a for-loop or the function find as follow:



              let found = items.find(d => d.year === year);
              if (found) return found.price;


              Or a vanilla for-loop:



              for (let i = 0; i < items.length; i++) 
              if (items[i].year === year) return items[i].price;





              share|improve this answer



























                1














                Because that return statement is inside of the handler of the function forEach, basically, you're returning the handler execution and not the main function.



                What you need to do is either to use a for-loop or the function find as follow:



                let found = items.find(d => d.year === year);
                if (found) return found.price;


                Or a vanilla for-loop:



                for (let i = 0; i < items.length; i++) 
                if (items[i].year === year) return items[i].price;





                share|improve this answer

























                  1












                  1








                  1







                  Because that return statement is inside of the handler of the function forEach, basically, you're returning the handler execution and not the main function.



                  What you need to do is either to use a for-loop or the function find as follow:



                  let found = items.find(d => d.year === year);
                  if (found) return found.price;


                  Or a vanilla for-loop:



                  for (let i = 0; i < items.length; i++) 
                  if (items[i].year === year) return items[i].price;





                  share|improve this answer













                  Because that return statement is inside of the handler of the function forEach, basically, you're returning the handler execution and not the main function.



                  What you need to do is either to use a for-loop or the function find as follow:



                  let found = items.find(d => d.year === year);
                  if (found) return found.price;


                  Or a vanilla for-loop:



                  for (let i = 0; i < items.length; i++) 
                  if (items[i].year === year) return items[i].price;






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 15 '18 at 1:34









                  EleEle

                  24k52150




                  24k52150





















                      -2














                      This needs ES6 (babel). Hope this helps! Got it from https://zellwk.com/blog/looping-through-js-objects/.






                      const year = 1910;

                      const items = [

                      name: 'gallon of gas',
                      year: 1910,
                      price: .12
                      ,

                      name: 'gallon of gas',
                      year: 1960,
                      price: .30
                      ,

                      name: 'gallon of gas',
                      year: 2010,
                      price: 2.80

                      ]
                      const values = Object.values(items)
                      for (const value of values)
                      //you can't return, but you can use the value or store it in a variable/array
                      console.log(value.price);








                      share|improve this answer























                      • 1) Calling Object.values() on an array will just return the array, so you can get rid of that and don't need ES6. 2) Your solution prints out the prices (same as just doing items.forEach(i => console.log(i.price))), it doesn't perform a lookup based on the year as was asked in the question.

                        – Robby Cornelissen
                        Nov 15 '18 at 1:48















                      -2














                      This needs ES6 (babel). Hope this helps! Got it from https://zellwk.com/blog/looping-through-js-objects/.






                      const year = 1910;

                      const items = [

                      name: 'gallon of gas',
                      year: 1910,
                      price: .12
                      ,

                      name: 'gallon of gas',
                      year: 1960,
                      price: .30
                      ,

                      name: 'gallon of gas',
                      year: 2010,
                      price: 2.80

                      ]
                      const values = Object.values(items)
                      for (const value of values)
                      //you can't return, but you can use the value or store it in a variable/array
                      console.log(value.price);








                      share|improve this answer























                      • 1) Calling Object.values() on an array will just return the array, so you can get rid of that and don't need ES6. 2) Your solution prints out the prices (same as just doing items.forEach(i => console.log(i.price))), it doesn't perform a lookup based on the year as was asked in the question.

                        – Robby Cornelissen
                        Nov 15 '18 at 1:48













                      -2












                      -2








                      -2







                      This needs ES6 (babel). Hope this helps! Got it from https://zellwk.com/blog/looping-through-js-objects/.






                      const year = 1910;

                      const items = [

                      name: 'gallon of gas',
                      year: 1910,
                      price: .12
                      ,

                      name: 'gallon of gas',
                      year: 1960,
                      price: .30
                      ,

                      name: 'gallon of gas',
                      year: 2010,
                      price: 2.80

                      ]
                      const values = Object.values(items)
                      for (const value of values)
                      //you can't return, but you can use the value or store it in a variable/array
                      console.log(value.price);








                      share|improve this answer













                      This needs ES6 (babel). Hope this helps! Got it from https://zellwk.com/blog/looping-through-js-objects/.






                      const year = 1910;

                      const items = [

                      name: 'gallon of gas',
                      year: 1910,
                      price: .12
                      ,

                      name: 'gallon of gas',
                      year: 1960,
                      price: .30
                      ,

                      name: 'gallon of gas',
                      year: 2010,
                      price: 2.80

                      ]
                      const values = Object.values(items)
                      for (const value of values)
                      //you can't return, but you can use the value or store it in a variable/array
                      console.log(value.price);








                      const year = 1910;

                      const items = [

                      name: 'gallon of gas',
                      year: 1910,
                      price: .12
                      ,

                      name: 'gallon of gas',
                      year: 1960,
                      price: .30
                      ,

                      name: 'gallon of gas',
                      year: 2010,
                      price: 2.80

                      ]
                      const values = Object.values(items)
                      for (const value of values)
                      //you can't return, but you can use the value or store it in a variable/array
                      console.log(value.price);





                      const year = 1910;

                      const items = [

                      name: 'gallon of gas',
                      year: 1910,
                      price: .12
                      ,

                      name: 'gallon of gas',
                      year: 1960,
                      price: .30
                      ,

                      name: 'gallon of gas',
                      year: 2010,
                      price: 2.80

                      ]
                      const values = Object.values(items)
                      for (const value of values)
                      //you can't return, but you can use the value or store it in a variable/array
                      console.log(value.price);






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 15 '18 at 1:40









                      fifn2 Confidentialfifn2 Confidential

                      368




                      368












                      • 1) Calling Object.values() on an array will just return the array, so you can get rid of that and don't need ES6. 2) Your solution prints out the prices (same as just doing items.forEach(i => console.log(i.price))), it doesn't perform a lookup based on the year as was asked in the question.

                        – Robby Cornelissen
                        Nov 15 '18 at 1:48

















                      • 1) Calling Object.values() on an array will just return the array, so you can get rid of that and don't need ES6. 2) Your solution prints out the prices (same as just doing items.forEach(i => console.log(i.price))), it doesn't perform a lookup based on the year as was asked in the question.

                        – Robby Cornelissen
                        Nov 15 '18 at 1:48
















                      1) Calling Object.values() on an array will just return the array, so you can get rid of that and don't need ES6. 2) Your solution prints out the prices (same as just doing items.forEach(i => console.log(i.price))), it doesn't perform a lookup based on the year as was asked in the question.

                      – Robby Cornelissen
                      Nov 15 '18 at 1:48





                      1) Calling Object.values() on an array will just return the array, so you can get rid of that and don't need ES6. 2) Your solution prints out the prices (same as just doing items.forEach(i => console.log(i.price))), it doesn't perform a lookup based on the year as was asked in the question.

                      – Robby Cornelissen
                      Nov 15 '18 at 1:48

















                      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%2f53311197%2fhow-do-i-return-the-object-i-want-by-using-a-key-in-a-foreach-loop%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







                      這個網誌中的熱門文章

                      Barbados

                      How to read a connectionString WITH PROVIDER in .NET Core?

                      Node.js Script on GitHub Pages or Amazon S3