我有一个像这样的 JSON 文件,总结一下:
{
"id": "1",
"country": "Brazil",
"state": [
{"id": "1", "name": "Acre",
"city": [ { "id": "1", "name": "Rio Branco"},
{ "id": "2", "name": "Xapuri"},
{ "id": "3", "name": "Cruzeiro do Sul"} ]
}
我在 View 中创建了 3 个选择选项,我必须首先选择国家/地区,然后根据国家/地区 ID,我需要用州填充第二个选择选项。选择州后,我需要在第三个选择选项中填写城市。
我创建了返回所有 JSON 文件的 PlacesService:
getPlaces() {
return this.http.get('assets/database/places.json')
.map( (res: Response) => res.json());
}
然后在我的组件中我调用此服务并且运行良好:
this.placesService.getPlaces().subscribe(dados => this.places= dados);
好吧,我知道如何返回 JSON 文件的所有数据,但我不知道如何搜索 JSON 文件内的特定 id 并仅返回与这些 ID 相关的对象。
我想知道如何解决这个问题以及最佳实践是什么,使用唯一 json 文件中的所有对象或划分在其他 json 文件中(例如:countries.json、states.json、cities.json)
最佳答案
更有效的方法是将它们划分为单独的平面数组,并添加“外键”,例如将 stateId
添加到城市,将 countryId
添加到州。
如果您决定不进行划分,则可以使用 Array.prototype.find 从嵌套对象中查找内容:
getCountry(id) {
return this.countries.find(c => c.id === id);
}
getState(id, country) {
return country.state.find(s => s.id === id);
}
getCity(id,state) {
return state.city.find(c => c.id === id);
}
const city = this.getCity('2', getState('1', getCountry('1'))); // Xapuri
正如您所见,3 个平面数组会让事情变得更简单。您可以通过简单的查找调用从所有城市中按 ID 查找城市,或通过过滤查找某个州的所有城市:
const acreCities = cities.filter(c => c.stateId === '1');
关于angular - 使用 Angular 2+ 在 JSON 文件中按 ID 搜索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49632512/