javascript function to search for object property and return value












0















I have a string:
const phrase = "there is a blue bird in the forest";



and an object:



const color = {
'blue': 20,
'red': 10,
'yellow': 5
};


I want to write a Javascript function that checks if the string contains any of the property of the color object and, if so, return the value for the matched property, so in the example above, it will return 20.



I'm using Lodash and I can't figure out how to write this function (_.some, _.find?)










share|improve this question

























  • Welcome to Stack Overflow :) Could you provide what you tried already?

    – sp00m
    Nov 23 '18 at 11:46
















0















I have a string:
const phrase = "there is a blue bird in the forest";



and an object:



const color = {
'blue': 20,
'red': 10,
'yellow': 5
};


I want to write a Javascript function that checks if the string contains any of the property of the color object and, if so, return the value for the matched property, so in the example above, it will return 20.



I'm using Lodash and I can't figure out how to write this function (_.some, _.find?)










share|improve this question

























  • Welcome to Stack Overflow :) Could you provide what you tried already?

    – sp00m
    Nov 23 '18 at 11:46














0












0








0


1






I have a string:
const phrase = "there is a blue bird in the forest";



and an object:



const color = {
'blue': 20,
'red': 10,
'yellow': 5
};


I want to write a Javascript function that checks if the string contains any of the property of the color object and, if so, return the value for the matched property, so in the example above, it will return 20.



I'm using Lodash and I can't figure out how to write this function (_.some, _.find?)










share|improve this question
















I have a string:
const phrase = "there is a blue bird in the forest";



and an object:



const color = {
'blue': 20,
'red': 10,
'yellow': 5
};


I want to write a Javascript function that checks if the string contains any of the property of the color object and, if so, return the value for the matched property, so in the example above, it will return 20.



I'm using Lodash and I can't figure out how to write this function (_.some, _.find?)







javascript lodash






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 12:21









Pranesh Janarthanan

489616




489616










asked Nov 23 '18 at 11:44









Anthony BrebionAnthony Brebion

81




81













  • Welcome to Stack Overflow :) Could you provide what you tried already?

    – sp00m
    Nov 23 '18 at 11:46



















  • Welcome to Stack Overflow :) Could you provide what you tried already?

    – sp00m
    Nov 23 '18 at 11:46

















Welcome to Stack Overflow :) Could you provide what you tried already?

– sp00m
Nov 23 '18 at 11:46





Welcome to Stack Overflow :) Could you provide what you tried already?

– sp00m
Nov 23 '18 at 11:46












8 Answers
8






active

oldest

votes


















1














If you need to get the total value of all colors in a string, you can use Array.reduce() (or lodash's _.reduce()). Change the phrase to lower case, split it by spaces, reduce, and take sum the value of the color (or 0 for other words):






const color = {
'blue': 20,
'red': 10,
'yellow': 5
};

const getColorsValue = (p) =>
p.toLowerCase()
.split(/s+/)
.reduce((s, w) => s + (color[w] || 0), 0);

console.log(getColorsValue('there is a blue bird in the forest')); // 20

console.log(getColorsValue('there is a blue bird in the red forest')); // 30








share|improve this answer































    0














    This will be useful for you, check this out or find code below: https://dustinpfister.github.io/2017/09/14/lodash-find/



    var db_array = [

    {
    name : 'Dave',
    sex : 'male',
    age : 34
    },

    {
    name: 'Jake',
    sex : 'male',
    age : 22
    },

    {
    name :'Jane',
    sex : 'female',
    age : 27
    }


    ],

    // find dave
    q = _.find(db_array, {name:'Dave'});

    console.log(q); // {name:'Dave',sex:male,age:34}





    share|improve this answer































      0














      Try Underscore.js Library. _.where(list, properties)






      share|improve this answer































        0














        This should help you!



        const phrase = "there is a blue bird in the forest";
        const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

        const phraseValues = phrase.split(' ');
        const colorValues = Object.keys(color)

        const isKeyPresent = !!_.intersection(phraseValues , colorValues).length





        share|improve this answer































          0














          We can achieve this utilising JavaScript's Object.keys() and .find()






          const phrase = "there is a blue bird in the forest";
          const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

          const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];

          console.log(result); // 20








          share|improve this answer

































            0














            Using js:






            const phrase = "there is a blue bird in the forest";

            const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

            let key = Object.keys(color).find(color => phrase.includes(color));

            if(key) console.log(color[key]);








            share|improve this answer

































              0














              You can use Array.flatMap and Array.split as well






              const phrase = "there is a blue bird in the forest";

              const color = {
              'blue': 20,
              'red': 10,
              'yellow': 5
              };

              let res = phrase.split(' ').flatMap(d => color[d] || )

              console.log(res[0] || 'No color is present')








              share|improve this answer

































                0














                You could also use the String.replace handler inside an Array.reduce on the colors to go though each and calculate the final sum.






                const data = "blue and red bird with blue feathers"
                const color = { 'blue': 20, 'red': 10, 'yellow': 5 }

                const result = Object.keys(color).reduce((r, k) =>
                (data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)

                console.log(result) // 50 since it has 2 "blue" and 1 "red"








                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%2f53446083%2fjavascript-function-to-search-for-object-property-and-return-value%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  8 Answers
                  8






                  active

                  oldest

                  votes








                  8 Answers
                  8






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  1














                  If you need to get the total value of all colors in a string, you can use Array.reduce() (or lodash's _.reduce()). Change the phrase to lower case, split it by spaces, reduce, and take sum the value of the color (or 0 for other words):






                  const color = {
                  'blue': 20,
                  'red': 10,
                  'yellow': 5
                  };

                  const getColorsValue = (p) =>
                  p.toLowerCase()
                  .split(/s+/)
                  .reduce((s, w) => s + (color[w] || 0), 0);

                  console.log(getColorsValue('there is a blue bird in the forest')); // 20

                  console.log(getColorsValue('there is a blue bird in the red forest')); // 30








                  share|improve this answer




























                    1














                    If you need to get the total value of all colors in a string, you can use Array.reduce() (or lodash's _.reduce()). Change the phrase to lower case, split it by spaces, reduce, and take sum the value of the color (or 0 for other words):






                    const color = {
                    'blue': 20,
                    'red': 10,
                    'yellow': 5
                    };

                    const getColorsValue = (p) =>
                    p.toLowerCase()
                    .split(/s+/)
                    .reduce((s, w) => s + (color[w] || 0), 0);

                    console.log(getColorsValue('there is a blue bird in the forest')); // 20

                    console.log(getColorsValue('there is a blue bird in the red forest')); // 30








                    share|improve this answer


























                      1












                      1








                      1







                      If you need to get the total value of all colors in a string, you can use Array.reduce() (or lodash's _.reduce()). Change the phrase to lower case, split it by spaces, reduce, and take sum the value of the color (or 0 for other words):






                      const color = {
                      'blue': 20,
                      'red': 10,
                      'yellow': 5
                      };

                      const getColorsValue = (p) =>
                      p.toLowerCase()
                      .split(/s+/)
                      .reduce((s, w) => s + (color[w] || 0), 0);

                      console.log(getColorsValue('there is a blue bird in the forest')); // 20

                      console.log(getColorsValue('there is a blue bird in the red forest')); // 30








                      share|improve this answer













                      If you need to get the total value of all colors in a string, you can use Array.reduce() (or lodash's _.reduce()). Change the phrase to lower case, split it by spaces, reduce, and take sum the value of the color (or 0 for other words):






                      const color = {
                      'blue': 20,
                      'red': 10,
                      'yellow': 5
                      };

                      const getColorsValue = (p) =>
                      p.toLowerCase()
                      .split(/s+/)
                      .reduce((s, w) => s + (color[w] || 0), 0);

                      console.log(getColorsValue('there is a blue bird in the forest')); // 20

                      console.log(getColorsValue('there is a blue bird in the red forest')); // 30








                      const color = {
                      'blue': 20,
                      'red': 10,
                      'yellow': 5
                      };

                      const getColorsValue = (p) =>
                      p.toLowerCase()
                      .split(/s+/)
                      .reduce((s, w) => s + (color[w] || 0), 0);

                      console.log(getColorsValue('there is a blue bird in the forest')); // 20

                      console.log(getColorsValue('there is a blue bird in the red forest')); // 30





                      const color = {
                      'blue': 20,
                      'red': 10,
                      'yellow': 5
                      };

                      const getColorsValue = (p) =>
                      p.toLowerCase()
                      .split(/s+/)
                      .reduce((s, w) => s + (color[w] || 0), 0);

                      console.log(getColorsValue('there is a blue bird in the forest')); // 20

                      console.log(getColorsValue('there is a blue bird in the red forest')); // 30






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 23 '18 at 12:35









                      Ori DroriOri Drori

                      77.3k138292




                      77.3k138292

























                          0














                          This will be useful for you, check this out or find code below: https://dustinpfister.github.io/2017/09/14/lodash-find/



                          var db_array = [

                          {
                          name : 'Dave',
                          sex : 'male',
                          age : 34
                          },

                          {
                          name: 'Jake',
                          sex : 'male',
                          age : 22
                          },

                          {
                          name :'Jane',
                          sex : 'female',
                          age : 27
                          }


                          ],

                          // find dave
                          q = _.find(db_array, {name:'Dave'});

                          console.log(q); // {name:'Dave',sex:male,age:34}





                          share|improve this answer




























                            0














                            This will be useful for you, check this out or find code below: https://dustinpfister.github.io/2017/09/14/lodash-find/



                            var db_array = [

                            {
                            name : 'Dave',
                            sex : 'male',
                            age : 34
                            },

                            {
                            name: 'Jake',
                            sex : 'male',
                            age : 22
                            },

                            {
                            name :'Jane',
                            sex : 'female',
                            age : 27
                            }


                            ],

                            // find dave
                            q = _.find(db_array, {name:'Dave'});

                            console.log(q); // {name:'Dave',sex:male,age:34}





                            share|improve this answer


























                              0












                              0








                              0







                              This will be useful for you, check this out or find code below: https://dustinpfister.github.io/2017/09/14/lodash-find/



                              var db_array = [

                              {
                              name : 'Dave',
                              sex : 'male',
                              age : 34
                              },

                              {
                              name: 'Jake',
                              sex : 'male',
                              age : 22
                              },

                              {
                              name :'Jane',
                              sex : 'female',
                              age : 27
                              }


                              ],

                              // find dave
                              q = _.find(db_array, {name:'Dave'});

                              console.log(q); // {name:'Dave',sex:male,age:34}





                              share|improve this answer













                              This will be useful for you, check this out or find code below: https://dustinpfister.github.io/2017/09/14/lodash-find/



                              var db_array = [

                              {
                              name : 'Dave',
                              sex : 'male',
                              age : 34
                              },

                              {
                              name: 'Jake',
                              sex : 'male',
                              age : 22
                              },

                              {
                              name :'Jane',
                              sex : 'female',
                              age : 27
                              }


                              ],

                              // find dave
                              q = _.find(db_array, {name:'Dave'});

                              console.log(q); // {name:'Dave',sex:male,age:34}






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 23 '18 at 11:52









                              shadowman_93shadowman_93

                              15712




                              15712























                                  0














                                  Try Underscore.js Library. _.where(list, properties)






                                  share|improve this answer




























                                    0














                                    Try Underscore.js Library. _.where(list, properties)






                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      Try Underscore.js Library. _.where(list, properties)






                                      share|improve this answer













                                      Try Underscore.js Library. _.where(list, properties)







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 23 '18 at 11:55









                                      Pranesh JanarthananPranesh Janarthanan

                                      489616




                                      489616























                                          0














                                          This should help you!



                                          const phrase = "there is a blue bird in the forest";
                                          const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                          const phraseValues = phrase.split(' ');
                                          const colorValues = Object.keys(color)

                                          const isKeyPresent = !!_.intersection(phraseValues , colorValues).length





                                          share|improve this answer




























                                            0














                                            This should help you!



                                            const phrase = "there is a blue bird in the forest";
                                            const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                            const phraseValues = phrase.split(' ');
                                            const colorValues = Object.keys(color)

                                            const isKeyPresent = !!_.intersection(phraseValues , colorValues).length





                                            share|improve this answer


























                                              0












                                              0








                                              0







                                              This should help you!



                                              const phrase = "there is a blue bird in the forest";
                                              const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                              const phraseValues = phrase.split(' ');
                                              const colorValues = Object.keys(color)

                                              const isKeyPresent = !!_.intersection(phraseValues , colorValues).length





                                              share|improve this answer













                                              This should help you!



                                              const phrase = "there is a blue bird in the forest";
                                              const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                              const phraseValues = phrase.split(' ');
                                              const colorValues = Object.keys(color)

                                              const isKeyPresent = !!_.intersection(phraseValues , colorValues).length






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Nov 23 '18 at 12:01









                                              Diljohn5741Diljohn5741

                                              38916




                                              38916























                                                  0














                                                  We can achieve this utilising JavaScript's Object.keys() and .find()






                                                  const phrase = "there is a blue bird in the forest";
                                                  const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                  const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];

                                                  console.log(result); // 20








                                                  share|improve this answer






























                                                    0














                                                    We can achieve this utilising JavaScript's Object.keys() and .find()






                                                    const phrase = "there is a blue bird in the forest";
                                                    const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                    const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];

                                                    console.log(result); // 20








                                                    share|improve this answer




























                                                      0












                                                      0








                                                      0







                                                      We can achieve this utilising JavaScript's Object.keys() and .find()






                                                      const phrase = "there is a blue bird in the forest";
                                                      const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                      const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];

                                                      console.log(result); // 20








                                                      share|improve this answer















                                                      We can achieve this utilising JavaScript's Object.keys() and .find()






                                                      const phrase = "there is a blue bird in the forest";
                                                      const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                      const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];

                                                      console.log(result); // 20








                                                      const phrase = "there is a blue bird in the forest";
                                                      const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                      const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];

                                                      console.log(result); // 20





                                                      const phrase = "there is a blue bird in the forest";
                                                      const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                      const result = color[Object.keys(color).find(v => phrase.indexOf(v) !== -1)];

                                                      console.log(result); // 20






                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Nov 23 '18 at 12:49









                                                      Nitish Narang

                                                      2,9401815




                                                      2,9401815










                                                      answered Nov 23 '18 at 11:53









                                                      Benjamin RussellBenjamin Russell

                                                      1296




                                                      1296























                                                          0














                                                          Using js:






                                                          const phrase = "there is a blue bird in the forest";

                                                          const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                          let key = Object.keys(color).find(color => phrase.includes(color));

                                                          if(key) console.log(color[key]);








                                                          share|improve this answer






























                                                            0














                                                            Using js:






                                                            const phrase = "there is a blue bird in the forest";

                                                            const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                            let key = Object.keys(color).find(color => phrase.includes(color));

                                                            if(key) console.log(color[key]);








                                                            share|improve this answer




























                                                              0












                                                              0








                                                              0







                                                              Using js:






                                                              const phrase = "there is a blue bird in the forest";

                                                              const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                              let key = Object.keys(color).find(color => phrase.includes(color));

                                                              if(key) console.log(color[key]);








                                                              share|improve this answer















                                                              Using js:






                                                              const phrase = "there is a blue bird in the forest";

                                                              const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                              let key = Object.keys(color).find(color => phrase.includes(color));

                                                              if(key) console.log(color[key]);








                                                              const phrase = "there is a blue bird in the forest";

                                                              const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                              let key = Object.keys(color).find(color => phrase.includes(color));

                                                              if(key) console.log(color[key]);





                                                              const phrase = "there is a blue bird in the forest";

                                                              const color = { 'blue': 20, 'red': 10, 'yellow': 5 };

                                                              let key = Object.keys(color).find(color => phrase.includes(color));

                                                              if(key) console.log(color[key]);






                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Nov 23 '18 at 12:55









                                                              Nitish Narang

                                                              2,9401815




                                                              2,9401815










                                                              answered Nov 23 '18 at 11:52









                                                              Sagar JajoriyaSagar Jajoriya

                                                              1,8261310




                                                              1,8261310























                                                                  0














                                                                  You can use Array.flatMap and Array.split as well






                                                                  const phrase = "there is a blue bird in the forest";

                                                                  const color = {
                                                                  'blue': 20,
                                                                  'red': 10,
                                                                  'yellow': 5
                                                                  };

                                                                  let res = phrase.split(' ').flatMap(d => color[d] || )

                                                                  console.log(res[0] || 'No color is present')








                                                                  share|improve this answer






























                                                                    0














                                                                    You can use Array.flatMap and Array.split as well






                                                                    const phrase = "there is a blue bird in the forest";

                                                                    const color = {
                                                                    'blue': 20,
                                                                    'red': 10,
                                                                    'yellow': 5
                                                                    };

                                                                    let res = phrase.split(' ').flatMap(d => color[d] || )

                                                                    console.log(res[0] || 'No color is present')








                                                                    share|improve this answer




























                                                                      0












                                                                      0








                                                                      0







                                                                      You can use Array.flatMap and Array.split as well






                                                                      const phrase = "there is a blue bird in the forest";

                                                                      const color = {
                                                                      'blue': 20,
                                                                      'red': 10,
                                                                      'yellow': 5
                                                                      };

                                                                      let res = phrase.split(' ').flatMap(d => color[d] || )

                                                                      console.log(res[0] || 'No color is present')








                                                                      share|improve this answer















                                                                      You can use Array.flatMap and Array.split as well






                                                                      const phrase = "there is a blue bird in the forest";

                                                                      const color = {
                                                                      'blue': 20,
                                                                      'red': 10,
                                                                      'yellow': 5
                                                                      };

                                                                      let res = phrase.split(' ').flatMap(d => color[d] || )

                                                                      console.log(res[0] || 'No color is present')








                                                                      const phrase = "there is a blue bird in the forest";

                                                                      const color = {
                                                                      'blue': 20,
                                                                      'red': 10,
                                                                      'yellow': 5
                                                                      };

                                                                      let res = phrase.split(' ').flatMap(d => color[d] || )

                                                                      console.log(res[0] || 'No color is present')





                                                                      const phrase = "there is a blue bird in the forest";

                                                                      const color = {
                                                                      'blue': 20,
                                                                      'red': 10,
                                                                      'yellow': 5
                                                                      };

                                                                      let res = phrase.split(' ').flatMap(d => color[d] || )

                                                                      console.log(res[0] || 'No color is present')






                                                                      share|improve this answer














                                                                      share|improve this answer



                                                                      share|improve this answer








                                                                      edited Nov 23 '18 at 17:01

























                                                                      answered Nov 23 '18 at 12:43









                                                                      Nitish NarangNitish Narang

                                                                      2,9401815




                                                                      2,9401815























                                                                          0














                                                                          You could also use the String.replace handler inside an Array.reduce on the colors to go though each and calculate the final sum.






                                                                          const data = "blue and red bird with blue feathers"
                                                                          const color = { 'blue': 20, 'red': 10, 'yellow': 5 }

                                                                          const result = Object.keys(color).reduce((r, k) =>
                                                                          (data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)

                                                                          console.log(result) // 50 since it has 2 "blue" and 1 "red"








                                                                          share|improve this answer




























                                                                            0














                                                                            You could also use the String.replace handler inside an Array.reduce on the colors to go though each and calculate the final sum.






                                                                            const data = "blue and red bird with blue feathers"
                                                                            const color = { 'blue': 20, 'red': 10, 'yellow': 5 }

                                                                            const result = Object.keys(color).reduce((r, k) =>
                                                                            (data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)

                                                                            console.log(result) // 50 since it has 2 "blue" and 1 "red"








                                                                            share|improve this answer


























                                                                              0












                                                                              0








                                                                              0







                                                                              You could also use the String.replace handler inside an Array.reduce on the colors to go though each and calculate the final sum.






                                                                              const data = "blue and red bird with blue feathers"
                                                                              const color = { 'blue': 20, 'red': 10, 'yellow': 5 }

                                                                              const result = Object.keys(color).reduce((r, k) =>
                                                                              (data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)

                                                                              console.log(result) // 50 since it has 2 "blue" and 1 "red"








                                                                              share|improve this answer













                                                                              You could also use the String.replace handler inside an Array.reduce on the colors to go though each and calculate the final sum.






                                                                              const data = "blue and red bird with blue feathers"
                                                                              const color = { 'blue': 20, 'red': 10, 'yellow': 5 }

                                                                              const result = Object.keys(color).reduce((r, k) =>
                                                                              (data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)

                                                                              console.log(result) // 50 since it has 2 "blue" and 1 "red"








                                                                              const data = "blue and red bird with blue feathers"
                                                                              const color = { 'blue': 20, 'red': 10, 'yellow': 5 }

                                                                              const result = Object.keys(color).reduce((r, k) =>
                                                                              (data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)

                                                                              console.log(result) // 50 since it has 2 "blue" and 1 "red"





                                                                              const data = "blue and red bird with blue feathers"
                                                                              const color = { 'blue': 20, 'red': 10, 'yellow': 5 }

                                                                              const result = Object.keys(color).reduce((r, k) =>
                                                                              (data.replace(new RegExp(k, 'g'), () => r += color[k]), r), 0)

                                                                              console.log(result) // 50 since it has 2 "blue" and 1 "red"






                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Nov 24 '18 at 6:26









                                                                              AkrionAkrion

                                                                              9,45511224




                                                                              9,45511224






























                                                                                  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%2f53446083%2fjavascript-function-to-search-for-object-property-and-return-value%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

                                                                                  Ottavio Pratesi

                                                                                  Tricia Helfer

                                                                                  15 giugno