繁体   English   中英

javascript函数搜索对象属性并返回值

[英]javascript function to search for object property and return value

我有一个字符串: const phrase = "there is a blue bird in the forest";

和一个对象:

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

我想编写一个Javascript函数,检查字符串是否包含颜色对象的任何属性,如果是,则返回匹配属性的值,因此在上面的示例中,它将返回20。

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

如果需要获取字符串中所有颜色的总值,则可以使用Array.reduce() (或lodash的_.reduce() )。 将词组更改为小写,将其用空格分开,减少并求和颜色的值(或换句话说,为0):

 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 

这对您很有用,请查看此代码或在下面找到代码: 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}

使用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]); 

我们可以利用JavaScript的Object.keys().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 

尝试使用Underscore.js库 _.where(list, properties)

这应该对您有帮助!

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

您也可以使用Array.flatMapArray.split

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

您还可以在Array.reduce内使用String.replace处理函数对每种颜色进行计算并计算最终的总和。

 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" 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM