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

Developing an Azure pipeline to generate artifacts for an Angular Universal application

I am currently facing an issue with deploying my Angular Universal app to Azure Web App Service. Running npm run build:ssr && npm run serve:ssr locally works perfectly fine. Similarly, running npm run start without ssr rendering also works smoothly ...

Comparing values between two JSON objects in Angular 8: A guide

I need to compare the values of two objects, obj1 and obj2, by ignoring keys that are missing in either object. If all key-value pairs are equal, return false; otherwise, return true. For example: If 'id' is present in obj1 but not in obj2, it s ...

New from Firefox 89: The afterprint event!

Having an issue with this fragment of code: const afterPrint = () => { this.location.back(); window.removeEventListener('afterprint', afterPrint); }; window.addEventListener('afterprint', afterPrint); window.print(); I&apos ...

Checking constructor arguments and code style issues

I need to ensure that the constructor parameter is validated correctly when an instance of a class is created. The parameter must be an object that contains exactly all the properties, with the appropriate types as specified in the class definition. If t ...

How to dynamically style a NgBootstrap modal in Angular during runtime

One of the features of my application is the ability to swap themes at runtime. The primary component in my app is called BaseComponent, which is added to my AppComponent and includes a theme property. This theme property represents a class that is applie ...

Encountering an issue upon launching the application: "Error: Token is required in order to proceed!"

I encountered the following error. Can someone please point out what's causing it? How can I resolve this issue? Could there be something missing in main.ts? Error: (index):39 Error: Error: Token must be defined! at new BaseException (https:/ ...

Struggling to incorporate generics into a Typescript method without sacrificing the typing of object keys

Currently, I am working on a method in Typescript that is responsible for extracting allowable property types from an object of a constrained generic type. The scenario involves a type called ParticipantBase which consists of properties like first: string ...

tips for converting a single observable item into an observable list

Within my Angular project, there exists an observable object with the following structure: export interface FavoritesResponse { wallet: boolean; deposit: boolean; withdraw: boolean; transfer: boolean; exchange: boolean; ticket: boolean; accou ...

Error encountered in Typescript while attempting to $set a subdocument key value in MongoDB

This is a sample data entry. { _id: ObjectId('63e501cc2054071132171098'), name: 'Ricky', discriminator: 7706, registerTime: ISODate('2023-02-09T14:23:08.159Z'), friends: { '63e502f4e196ec7c04c4 ...

Trouble with Angular not Displaying BootStrap 5.0 Styles

Trying to implement both BootStrap and Angular into the project, I successfully applied the styles by adding the following line in the index file: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="sty ...

Encountered a higher number of hooks rendered compared to the previous render error on a component without any conditional hook usage

Within my codebase, I have a component that is responsible for rendering a clickable link to initiate a file upload process. import { gql, useLazyQuery, useMutation } from '@apollo/client'; import { useEffect, useState } from 'react'; i ...

Develop an interface in TypeScript for intricate data structures

Displayed below is a variable that contains a collection of objects: scenes = { sky: { image: 'assets/1.jpg', points: { blue_area: { x: 1, y: 2 }, } }, blue_area: { image: & ...

Craft a specialized script for manipulating the DOM

I'm currently working on a project using Angular 2. I have implemented a menu that should be able to close when a button is clicked. Instead of using a component for the menu, I want to keep it lightweight by placing it outside of Angular. However, I ...

Simulating service calls in Jest Tests for StencilJs

When testing my StencilJs application with Jest, I encountered an issue with mocking a service class method used in a component. The service class has only one function that prints text: The Component class: import {sayHello} from './helloworld-servi ...

Tips for integrating Angular Material styles into Sonarque

Can Sonarqube analyze my Angular application prominently using Angular Material? The styling I have is: .some-class { mat-icon { color: red; } } Since Angular Material is globally added through angular.json configuration, So ...

retrieve asynchronous data from the server using ngrx

How can I retrieve asynchronous data from the server? I am looking to save this data in a global store for future updates. I'm having trouble grasping the concept of asynchronous calls, such as in Redux. While I was able to understand it with simpl ...

Ending the Infinite Scroll in Ionic 3 When Data Runs Out

I am having an issue with my json data where I need to figure out how to stop the infinite scroll once there is no more data available. Can anyone help me implement this feature? Below is the code snippet for reference: handleDataLoad(currentCount) ...

Whenever signing in with Next Auth, the response consistently exhibits the values of "ok" being false and "status" being 302, even

I am currently using Next Auth with credentials to handle sign-ins. Below is the React sign-in function, which can be found at this link. signIn('credentials', { redirect: false, email: email, password: password, ...

There is no index signature that includes a parameter of type 'number' on the specified type xx

Here are the data types I am currently utilizing: export interface IHelpDeskTextData { supportPaneltext: ContactHelpdeskContex[]; selected?: number | null; brandOptions?: string[]; textPanel?: ITextPanel[]; } export class ContactHelpdeskContex { ...

Leverage the retrieved configuration within the forRoot function

Currently working on an Angular app that uses @ngx-translate. In my implementation, I am using TranslateModule.forRoot(...) to set up a TranslateLoader: @NgModule({ imports: [ TranslateModule.forRoot({ loader: { provide: TranslateLoade ...