Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

javascript - 使用Lodash在对象的任何属性值中查找部分字符串(Using Lodash to find a partial string in any property value of an object)

I want to use Lodash to return true when an object contains in any of its values, a match for a partial string.(我想使用Lodash在对象的任何值中包含部分字符串的匹配项时返回true 。)

I've tried this with _.includes as follows.(我已经尝试过使用_.includes如下。) const ob = {first: "Fred", last: "Flintstone",} const search = "stone"; const result = _.includes(ob, search) console.log(result); // false I've also tried this using a regular expression instead of a string for the search term.(我还尝试使用正则表达式而不是搜索项的字符串来进行此操作。) const search = /stone/gi; Both times result returns false .(两次result返回false 。) I want result to return true .(我希望result返回true 。) How can I do this in Lodash?(如何在Lodash中做到这一点?)   ask by Mowzer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use lodash's _.some() (which works with objects), and lodash/vanilla includes to find if the current property's value has the search string:(您可以使用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); // true <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script> And a lodash/fp version:(还有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); // true <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script> To handle case sensitivity and letters with diacritics, you can use _.deburr() (or the this answer ), and convert the text to lower case:(要使用变音符号处理区分大小写和字母,可以使用_.deburr() (或this 答案 ),并将文本转换为小写:) const normalize = str => _.toLower(_.deburr(str)) const includesValue = (val, obj) => { const search = normalize(val) return _.some(obj, v => normalize(v).includes(search)) } const obj = {first: "Fred", last: "Flintstoné",} const search = "Stone"; const result = includesValue(search, obj) console.log(result); // true <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...