简体   繁体   English

在数组对象中查找部分字符串文本

[英]Find partial string text in array object

Example: If I use the code below it works for the whole word "gorilla".示例:如果我使用下面的代码,它适用于整个单词“gorilla”。

How do I get it to work with "gor" or "illa" or "orill"...?我如何让它与“gor”或“illa”或“orill”一起工作......?

...(equivalent to a str like "%gor%" in mysql for example) ...(例如,相当于 mysql 中的“%gor%”之类的 str)

 const jungle = [ { name: "frog", threat: 0 }, { name: "monkey", threat: 5 }, { name: "gorilla", threat: 8 }, { name: "lion", threat: 10 } ]; const names = jungle.map(el => el.name); // returns true document.write(names.includes("gorilla"));

You can use find (or filter )您可以使用find (或filter

 const jungle = [ { name: "frog", threat: 0 }, { name: "monkey", threat: 5 }, { name: "gorilla", threat: 8 }, { name: "lion", threat: 10 } ]; const names = (partial) => jungle.find(el => el.name.includes(partial)).name; //You can also use "filter" method ==> //const names = (partial) => jungle.filter(el => el.name.includes(partial)).map(el => el.name) console.log(names("gor")) console.log(names("illa")) console.log(names("orill"))

 const jungle = [ { name: "frog", threat: 0 }, { name: "monkey", threat: 5 }, { name: "gorilla", threat: 8 }, { name: "lion", threat: 10 } ]; console.log(jungle.some(({name}) => "gorilla".includes(name))); // returns true

You need to find the object where the name includes the (partial) string, and return the name ;您需要find名称includes (部分)字符串的对象,并返回name otherwise return a default error string.否则返回默认错误字符串。

 const jungle = [ { name: "frog", threat: 0 }, { name: "monkey", threat: 5 }, { name: "gorilla", threat: 8 }, { name: "lion", threat: 10 } ]; function finder(jungle, str) { return jungle.find(obj => { return obj.name.includes(str); })?.name || 'No animal found'; } console.log(finder(jungle, 'gor')); console.log(finder(jungle, 'pas')); console.log(finder(jungle, 'illa')); console.log(finder(jungle, 'og')); console.log(finder(jungle, 'nk'));

Additional documentation附加文件

Use Array.filter to find all matches (or Array.find if you just want the first match).使用Array.filter查找所有匹配项(如果您只想要第一个匹配Array.find ,则使用 Array.find )。

Use String.match so that the search string can be either a string or a RegEx , the latter giving you the ability to use wildcards, exact match or more complex criteria.使用String.match以便搜索字符串可以是stringRegEx ,后者使您能够使用通配符、完全匹配或更复杂的条件。

 const jungle = [ { name: "frog", threat: 0 }, { name: "monkey", threat: 5 }, { name: "gorilla", threat: 8 }, { name: "lion", threat: 10 } ]; // find the animal whose name matches the regular expression function findAnimal(name) { return jungle.filter(animal => animal.name.match(name)); } console.log(findAnimal('gorilla')); console.log(findAnimal('on')); console.log(findAnimal(/^gor/)); console.log(findAnimal(/illa$/));

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

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