gpt4 book ai didi

javascript - 在 Angular 6 中使用 JSON 进行过滤

转载 作者:行者123 更新时间:2023-12-02 17:01:56 25 4
gpt4 key购买 nike

城市.json

[
{ "id": "1", "name": "Mumbai", "state": "Maharashtra" },
{ "id": "2", "name": "Delhi", "state": "Delhi" },
{ "id": "3", "name": "Bengaluru", "state": "Karnataka" },
{ "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
{ "id": "5", "name": "Hyderabad", "state": "Telangana" },
{ "id": "6", "name": "Chennai", "state": "Tamil Nadu" }
]

我的组件.html

<div class="search-container">
<h2>Find Location</h2>
<input #searchBoxL id="search-box-loc" (input)="searchForLocation(searchBoxL.value)" [(ngModel)]="selectedResultfilocation"
placeholder="city, province or region" />
<button (click)="searchJobMethod()"><i class="fa fa-search"></i></button>
<ul class="search-result">
<li *ngFor="let loc of searchFindLoopForLocation">
<a (click)="searchBoxL.value = loc;selectedResultfilocation = loc;">{{ loc }}</a>
</li>
</ul>
</div>

我的组件.ts

selectedResultfilocation: string;
SearchResultResponseForlocation;
searchFindLoopForLocation;
searchForLocation(term: string): void {
this.searchResultMethodForLocation(term);
}
searchResultMethodForLocation(fl: string){
this.http.get('/assets/js/cities.json' + term).pipe(
).subscribe(
data => {
this.SearchResultResponseForlocation = data.json();
console.log(this.SearchResultResponseForlocation[0].name);
this.searchFindLoopForLocation =
this.SearchResultResponseForlocation;
},
error => {
console.log("Error in recieving data");
},
() => {
console.log(this.SearchResultResponse);
}
);
}

我的问题是如何从 Angular 6 中给定的 JSON 结构中过滤名称。当我输入位置名称时,我可以获得名称的所有建议。请帮助我如何做到这一点,我是 angular 6 的新手。

最佳答案

如果我没答错你的问题,你不需要特定 Angular 东西;您始终可以按如下方式在 javaScript 中过滤 JSON -

var data = [
{ "id": "1", "name": "Mumbai", "state": "Maharashtra" },
{ "id": "2", "name": "Delhi", "state": "Delhi" },
{ "id": "3", "name": "Bengaluru", "state": "Karnataka" },
{ "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
{ "id": "5", "name": "Hyderabad", "state": "Telangana" },
{ "id": "6", "name": "Chennai", "state": "Tamil Nadu" }
];

var newData = filterData('Mumbai');

function filterData(locationName) {
return data.filter(object => {
return object['name'] == locationName;
});
}

console.log(newData);

如果您需要与实现相关的帮助,请引用以下内容 -

<input #searchBoxL id="search-box-loc" [(ngModel)]="selectedResultfilocation" (ngModelChange)="searchJobMethod()"
placeholder="city, province or region" />

searchJobMethod() {
searchFindLoopForLocation = data.filter(object => {
return object['name'] == selectedResultfilocation;
});
}

关于javascript - 在 Angular 6 中使用 JSON 进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53741079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com