Search code examples
javascriptlodash

javascript function to search for object property and return value


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?)


Solution

  • 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