Locate a specific item by its ID within a JSON file utilizing Angular version 2 or later

My JSON file structure is like the example below:

{
    "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"} ] 
}

In my view, I have set up 3 select options. The first one is for selecting a country, which will then populate the second select option with states based on the country ID. Upon selecting a state, the third select option should display cities related to that state.

I have implemented a PlacesService to fetch the JSON data:

getPlaces() {
    return this.http.get('assets/database/places.json')
    .map( (res: Response) => res.json());
}

In my component, I call the service as follows and it functions correctly:

this.placesService.getPlaces().subscribe(data => this.places = data);

While I can retrieve all the data from the JSON file, I am unsure how to search for a specific ID within the file and only return the object associated with that ID.

I am curious about the best approach to tackle this issue - should I store all objects in a single JSON file or divide them into separate files (e.g., countries.json, states.json, cities.json)?

Answer №1

To increase efficiency, it would be better to separate them into individual flat arrays and incorporate "foreign keys" such as stateId for cities and countryId for states.

If you opt not to divide, you could locate items within a nested object using Array.prototype.find, for instance:

fetchCountry(id) {
    return this.countries.find(country => country.id === id);
}

retrieveState(id, country) {
    return country.state.find(state => state.id === id);
}

obtainCity(id,state) {
    return state.city.find(city => city.id === id);
}

const selectedCity = this.obtainCity('2', retrieveState('1', fetchCountry('1'))); 
// This will find the city with ID '2' in Xapuri

Therefore, by utilizing 3 flat arrays, the process becomes more straightforward. You can easily search for a city by its ID among all cities or filter out all cities belonging to a specific state:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Importing Angular libraries with the * symbol

One of the key modules in my library is sha256. To import it, I had to use the following syntax: import sha256 from 'sha256'; However, while researching this issue, I came across a question on Stack Overflow titled: Errors when using MomentJS ...

Tap into the live monitoring feature of angular-cli build

Is there a way to integrate custom functionality with angular-cli's build/watch command? ng build /w This command creates files and places them in the project's /dist folder I am looking to automatically copy the contents of the dist folder ...

Tips for efficiently passing TypeScript constants to Vue templates without triggering excessive reactivity

I'm curious about the most efficient way to pass a constant value to a template. Currently, I am using the data property in Vue, but I believe that is better suited for state that changes over time as Vue adds event listeners to data properties. The c ...

Using Angular 4 and Bootstrap to create a Modal Component

I am contemplating the idea of integrating a component into an application that can function both as a Bootstrap modal and as a regular child component within a page. In the example provided on the referenced link, a component being used in a modal requir ...

Encountering an issue with the 'createObjectURL' function in URL, resulting in overload resolution failure when using npm file-saver

While working on my angular app, I encountered a situation where I needed to download user details uploaded as a Word document to my local machine using the angular app. Successfully, I was able to upload and save this data to my database, getting its byte ...

Create an object using a combination of different promises

Creating an object from multiple promise results can be done in a few different ways. One common method is using Promise.all like so: const allPromises = await Promise.all(asyncResult1, asyncResult2); allPromises.then([result1, result2] => { return { ...

Tips for effectively handling projects that call for varying versions of TypeScript within Visual Studio

In some cases, developers have had to downgrade their TypeScript version in order for it to work with a specific npm package version. Is it possible to do this with Visual Studio? I recently obtained a sample solution that utilized the angular2 npm packag ...

What is the best way to showcase images at random in Angular?

I am trying to display a random array of images in the UI, but I'm encountering an error with innerHTML when using the code below in TypeScript. randomPic(){ this.randomNum= Math.floor(Math.random() * this.myPix.length); console.log(this.rando ...

Only the (click) event is functional in Angular, while the (blur), (focus), and (focusout) events are not functioning

I have a unique HTML element as shown below <div (hover)="onHover()" (double-click)="onDoubleClick()" (resize)="resize()" (dragend)="dragEnd()"> These 4 functions are designed to display information onHover ...

The reason behind the ghost problem - classRef isn't recognized as a constructor

Recently, I encountered an issue where the app was not loading in the browser while running an Angular NX project locally with the command "start-dev": "nx run-many --target=serve --all". The screen would get stuck on our loading animat ...

The element 'commit' cannot be found within the property

I am facing an issue when transitioning from using Vuex in JavaScript to TypeScript. The error message Property 'commit' does not exist appears in Vuex's mutations: const mutations = { methodA (): none { this.commit('methodB' ...

Scrolling horizontally in Ionic framework

In regards to the response found on Ionic - Horizontal scroll tab for Categories, I have a question. I am curious about what needs to be included in the category.model. Can anyone provide some guidance? ...

Angular: Leveraging real-time data updates to populate an Angular Material Table by subscribing to a dynamic data variable in a service

Seeking guidance on how to set up a subscription to a dynamic variable (searchData - representing search results) for use as a data source in an Angular Material Table. I have a table-datasource.ts file where I want to subscribe to the search results from ...

Issue with Font Requests in Browsers when Using Angular 10 and SCSS with @font-face

I have a project built with Angular 10 that utilizes SCSS for styling. In my _typography.scss file, I have defined some @font-face rules pointing to the font files located in the assets/fonts directory. However, when I run the application, the browser does ...

How can you reposition a component within the dom using Angular?

Just started learning Angular, so I'm hoping this question is simple :) Without getting too specific with code, I could use some guidance to point me in the right direction. I'm currently developing a small shopping list application. The idea i ...

Exploring the functionality of Material components within a nested child component

I am facing an issue with my TestComponent, which uses a <mat-stepper> in its template. Due to the specific context of the stepper, I have to programmatically move to the next step instead of using the matStepperNext directive on a button. Here is a ...

Generating PDF files from HTML documents using Angular

I am currently working on an Angular 11 application and I have a specific requirement to download a PDF file from a given HTML content. The challenge is that the HTML content exists independent of my Angular app and looks something like this: < ...

How to ensure Angular mat-button-toggle elements are perfectly aligned within their respective groups

https://i.stack.imgur.com/Wjtn5.png Hello there, I'm trying to make the numbers in the first group match the style of the second group (noche, mañana...). I've set both the group and individual element width to 100%, but the numbers beyond 22 ...

Having trouble accessing a variable from the material theme in Angular 7

Currently, I am working with Angular 7.0.3 and endeavoring to establish an scss variable with the primary color of my material theme. // src/styles/_variables.scss @import "~@angular/material/theming"; @include mat-core(); $app-primary: mat-palette($mat-i ...

Could someone provide an explanation for the meaning of the phrase "class User extends Model<UserAttribute UserCreationAttribute>"?

View Image of the Issue I am puzzled by why we are utilizing both UserCreationAttribute and UserAttribute in that specific arrow, especially when UserCreationAttribute is created by omitting one field from UserAttribute. Can someone please clarify this fo ...