angular - 使用 Angular 2+ 在 JSON 文件中按 ID 搜索对象

标签 angular typescript angular5 angular-http

我有一个像这样的 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/

相关文章:

inheritance - 是否可以删除子类/接口(interface)中的继承字段/方法?

css - angular-dual-listbox - 隐藏按钮

angular - 使用 Angular CLI 时转译的 js 文件在哪里

javascript - Angular2/4 在请求后填充表单

调用服务后,Angular 2 无法在订阅方法中执行操作

angular - 当用户在 Angular 2 的 View 中更改某些内容时如何检测组件的更改?

javascript - Typescript/JSX - 通过引用分配一个类的实例

unit-testing - 如何在 Typescript 中对私有(private)方法进行单元测试

angular - 如何从 Angular 4 中的 httppost 方法将整数值传递给 Controller ​​?

node.js - Angular 和 Node.JS Express 如何在同一个端口运行?