您能告诉我如何使用Underscore.js查找首次出现的属性(无需完全匹配)吗?
我试过了。但是它只返回完全匹配的属性。让我们在我的列表中说```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(Rramas)
library(grDevices)
library(devtools)
```
就像townName
一样。但我也需要选择Rocky Point
。那我怎么能这样做呢?
Rocky
e.g。
var schoolDistrict = _.find(vm.schoolDistricts, function (d) { return d.townName
== result.data[0].PropertyData.School; });
答案 0 :(得分:1)
OP的反馈:我使用如下所示并正常工作:)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<span>span1</span>
<div class="el">div1</div>
<p class="big">paragraph A</p>
<p class="small">paragraph A</p>
</div>
另一种方式:
如果任一字符串是另一个字符串的子字符串,您可以进行原始检查。您还可以将字符串设置为小写以便更好地搜索:
var schoolDistrict = _.find(vm.schoolDistricts, function (s) { return
s.townName.toLowerCase().indexOf(result.data[0].PropertyData.School.toLowerCase(
)) !== -1; });
var schoolDistricts = [
{townName:'Rocky Point'},
{townName: 'Roc'}
];
var searchString = 'Rocky'.toLowerCase();
var res = _.find(schoolDistricts, function(s) {
var townName = s.townName.toLowerCase();
return townName.indexOf(searchString) !== -1 || searchString.indexOf(townName) !== -1;
});
console.log(res);
答案 1 :(得分:1)
使用RegExp模式测试名称是否包含文本,并使用i
标志忽略大小写:
var schoolDistricts = [{
townName: 'South Rock'
}, {
townName: 'Red Herring'
}, {
townName: 'Rocky Point'
}, {
townName: 'Whatnot'
}];
var school = 'Rocky'; // replacement for result.data[0].PropertyData.School
var pattern = new RegExp(school, 'i');
var result = _.find(schoolDistricts, function(d) {
return pattern.test(d.townName);
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>