【问题标题】:Search object by ID inside JSON file using Angular 2+使用 Angular 2+ 在 JSON 文件中按 ID 搜索对象
【发布时间】:2018-04-03 22:58:29
【问题描述】:

我有一个这样的 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"} ] 
}

我在视图中创建了 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、citys.json)

【问题讨论】:

    标签: angular typescript angular5 angular-http


    【解决方案1】:

    更有效的方法是将它们分成单独的平面数组,并将“外键”如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 个平面数组会使事情变得更简单。您可以通过简单的 find 调用从所有城市中通过 id 找到一个城市,或者通过过滤从一个州的所有城市中找到:

    const acreCities = cities.filter(c => c.stateId === '1');
    

    【讨论】:

    • 谢谢!不幸的是,有人否定了我的问题,但我搜索了很多并没有找到一个好的答案。你帮了我很多。
    • 支持您归零。我也没有真正看到拒绝投票的原因..问题对我来说是有效的。在没有评论和解释原因的情况下投反对票并不好。
    猜你喜欢
    • 2016-12-29
    • 2016-03-13
    • 2019-01-28
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多