当对象的任何值包含部分字符串的匹配项时,我想使用Lodash返回true。我已经用_.includes
进行了如下尝试。
const ob = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = _.includes(ob, search)
console.log(result); // false
我还尝试使用正则表达式而不是搜索项的字符串来进行此操作。
const search = /stone/gi;
两次result
返回false
。我希望result
返回true
。如何在Lodash中做到这一点?
答案 0 :(得分:1)
您可以find像这样object's values的数组中的部分字符串。
const ob = {
first: "Fred",
last: "Flintstone"
}
const search = "stone"
const isFound = Boolean(Object.values(ob).find(item => item.includes(search)))
console.log(isFound)
根据@Kobe的建议,您可以使用some而不是使用find
来评估Boolean()
的结果。
const ob = {
first: "Fred",
last: "Flintstone"
}
const search = "stone"
const isFound = Object.values(ob).some(item => item.includes(search))
console.log(isFound)
答案 1 :(得分:1)
您可以使用lodash的_.some()
(适用于对象),并且lodash / vanilla包括以查找当前属性的值是否具有搜索字符串:
const includesValue = (val, obj) => _.some(obj, v => _.includes(v, val))
const obj = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = includesValue(search, obj)
console.log(result); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
还有lodash / fp版本:
const includesValue = val => _.some(_.includes(val))
const obj = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = includesValue(search)(obj)
console.log(result); // false
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
答案 2 :(得分:0)
那不是lodash包含的内容。
您应该搜索对象的值,而不是对象本身。并且您应该依次检查每个值。
此外,您不需要lodash。
const ob = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = Object.values(ob).some(value => value.indexOf(search) !== -1);
console.log(result); // true
答案 3 :(得分:0)
如果要使用lodash,可以使用_filter。
const ob = {first: "Fred", last: "Flintstone",}
var filteredOb = _.filter(ob, function(elem) {
return elem.indexOf("stone") > -1;
});
console.log(filteredOb);