Javascript 使用自动完成过滤对象中的数组
我尝试使用两种过滤方法,基于字符串对对象中的数组进行过滤。这是我的物体看起来的样子Javascript 使用自动完成过滤对象中的数组,javascript,arrays,angular,typescript,Javascript,Arrays,Angular,Typescript,我尝试使用两种过滤方法,基于字符串对对象中的数组进行过滤。这是我的物体看起来的样子 [ { "cat": "Accommodation and Food Service Activities", "value": [ { "sic": "55", "desc": "Accommodation" }, { "sic": "56", "desc": "Food and beverag
[
{
"cat": "Accommodation and Food Service Activities",
"value": [
{
"sic": "55",
"desc": "Accommodation"
},
{
"sic": "56",
"desc": "Food and beverage service activities"
}
]
},
{
"cat": "Activities Of Extraterritorial Organisations and Bodies",
"value": [
{
"sic": "99",
"desc": "Activities of extraterritorial organisations and bodies"
}
]
}
]
我正在尝试筛选值.desc
并返回cat
这是我到目前为止所拥有的
filteredIndustries(industry: string) {
if (industry) {
return this.industries.filter(sector => {
if (sector.value) {
sector.value.findIndex( v => {
return v.desc.toString().toLowerCase().indexOf(industry.toString().toLowerCase()) === 0;
});
}
});
} else {
return this.industries;
}
这是我的html
<md-input-container>
<input mdInput placeholder="Industry" [mdAutocomplete]="auto" [formControl]="industryCtrl">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayIndustry.bind(this)">
<md-option *ngFor="let industry of filteredIndustry | async" [value]="industry">
{{ industry.cat }}
</md-option>
</md-autocomplete>
{{industry.cat}
因此,当我输入食物时,它应该过滤value.desc
并返回cat
,这应该是住宿和餐饮服务活动
但是我没有得到任何返回值,即使我的返回结果是真的
任何帮助都将不胜感激。您的
过滤器
回调函数缺少返回语句,如果findIndex
返回大于-1的值,则应返回true
filteredIndustries(industry: string) {
if (industry) {
return this.industries.filter(sector => {
if (sector.value) {
return -1 < sector.value.findIndex( v => { //HERE
return v.desc.toString().toLowerCase().indexOf(industry.toString().toLowerCase()) === 0;
});
}
});
} else {
return this.industries;
}
}
filteredIndustries(行业:字符串){
国际单项体育联合会(工业){
返回此.industries.filter(扇区=>{
if(部门价值){
return-1{//HERE
返回v.desc.toString().toLowerCase().indexOf(industry.toString().toLowerCase())==0;
});
}
});
}否则{
还这个产业,;
}
}
您可以使用some()
而不是findIndex()
<如果找不到指定的字符串,则code>indexOf返回-1
var行业=[
{
“cat”:“住宿和餐饮服务活动”,
“价值”:[
{
“原文如此”:“55”,
“描述”:“住宿”
},
{
“原文如此”:“56”,
“描述”:“餐饮服务活动”
}
]
},
{
“cat”:“域外组织和机构的活动”,
“价值”:[
{
“原文如此”:“99”,
“描述”:“域外组织和机构的活动”
}
]
}
]
var行业=‘食品’
var b=行业。过滤器(行业=>{
if(部门价值){
返回sector.value.some(v=>v.desc.toLowerCase().indexOf(industry)>=0);
}否则{
回归产业
}
});
console.log(b)
很遗憾,这没有返回值。无论如何谢谢你。排序我已经编辑了我的答案来证明我的代码是有效的。只是你传递给filter()的函数总是返回未定义的,并且它是一个“falsy”值,所以它会过滤掉数组中的所有元素。行业感谢你的帮助,这帮助我让它工作。欢迎来到so!这是一个很好的第一个问题,你发布了你的代码,并正确地解释了你的问题,使之更容易帮助你+1.