用于搜索对象属性和返回值的javascript函数

用于搜索对象属性和返回值的javascript函数,javascript,lodash,Javascript,Lodash,我有一个字符串: const短语=“森林里有一只蓝色的鸟” 和一个对象: const color = { 'blue': 20, 'red': 10, 'yellow': 5 }; 我想编写一个Javascript函数,检查字符串是否包含color对象的任何属性,如果包含,则返回匹配属性的值,因此在上面的示例中,它将返回20 我正在使用Lodash,但我不知道如何编写此函数(u.some,u.find?)这将对您有用,请查看此项或查找下面的代码: 使用js: const短语=“森林里有一只蓝

我有一个字符串:
const短语=“森林里有一只蓝色的鸟”

和一个对象:

const color = {
'blue': 20,
'red': 10,
'yellow': 5
};
我想编写一个Javascript函数,检查字符串是否包含color对象的任何属性,如果包含,则返回匹配属性的值,因此在上面的示例中,它将返回20


我正在使用Lodash,但我不知道如何编写此函数
(u.some,u.find?)

这将对您有用,请查看此项或查找下面的代码:

使用js:

const短语=“森林里有一只蓝色的鸟”;
常量颜色={‘蓝色’:20,‘红色’:10,‘黄色’:5};
让key=Object.keys(color.find)(color=>phrase.includes(color));

if(key)console.log(color[key])我们可以利用JavaScript的Object.keys().find()

const短语=“森林里有一只蓝色的鸟”;
常量颜色={‘蓝色’:20,‘红色’:10,‘黄色’:5};
const result=color[Object.keys(color.find)(v=>phrase.indexOf(v)!=-1)];
console.log(结果);//20
试试看<代码>\其中(列表、属性)

这应该对您有所帮助

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

如果需要获取字符串中所有颜色的总值,可以使用(或lodash)。将短语更改为小写,按空格拆分,减少,并将颜色值求和(或0表示其他单词):

const color={
“蓝色”:20,
“红色”:10,
“黄色”:5
};
常量getColorsValue=(p)=>
p、 toLowerCase()
.split(/\s+/)
.减少((s,w)=>s+(颜色[w]| | 0),0);
log(getColorsValue(“森林中有一只蓝色的鸟”);//20

log(getColorsValue(“红色森林中有一只蓝色的鸟”);//30
您也可以使用
数组.flatMap
数组.split

const短语=“森林里有一只蓝色的鸟”;
常量颜色={
“蓝色”:20,
“红色”:10,
“黄色”:5
};
让res=phrase.split(“”).flatMap(d=>color[d]| |[]))
log(res[0]| |“没有颜色存在”)
您还可以使用颜色上的处理程序遍历每个颜色并计算最终的和

const data=“蓝色和红色羽毛的鸟”
常量颜色={“蓝色”:20,“红色”:10,“黄色”:5}
const result=Object.keys(color).reduce((r,k)=>
(data.replace(新的RegExp(k,'g'),()=>r+=color[k]),r),0)
console.log(result)//50,因为它有2个“蓝色”和1个“红色”
欢迎使用堆栈溢出:)您能提供您已经尝试过的吗?
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