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

时间:2018-11-23 11:44:12

标签: javascript lodash

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

和一个对象

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

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

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

8 个答案:

答案 0 :(得分:1)

如果需要获取字符串中所有颜色的总值,则可以使用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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

我们可以使用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

答案 4 :(得分:0)

尝试Underscore.js Library_.where(list, properties)

答案 5 :(得分:0)

这应该对您有帮助!

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

答案 6 :(得分:0)

您也可以使用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')

答案 7 :(得分:0)

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

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"