Matching Arrays in Angular Made Easy

Hello friends! I'm seeking assistance since I'm a beginner in the world of Angular and TypeScript.

export class TopPage implements OnInit {
  //city = localStorage.getItem('city');
  city = 'bangalore';
  areas_array = {
    "bangalore": ['one', 'two'],
    "chennai": ['four', 'five'],
    "hyderabad": ['six', 'seven']
  };

  area;
}

if (city === areas_array) {
  //areas that matches the city
}

I am looking to retrieve the array within the areas_array that corresponds with the city. Also, is this the correct way to structure the areas_array?

Answer №1

Iterate through keys and check for a specific value:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  areas_array = {
    "bangalore": ['one', 'two'],
    "chennai": ['four', 'five'],
    "hyderabad": ['six', 'seven']
  };


  constructor() {
    let searchCity = 'bangalore';
    for (let key in this.areas_array) {
      if (key === searchCity) {
        console.log(this.areas_array[searchCity]);
      }
    }
  }

}

Check out the code on StackBlitz:https://stackblitz.com/edit/angular-qjndzg?file=src%2Fapp%2Fapp.component.ts

Answer №2

Using the Object.keys method to filter areas_array based on a specific city and then mapping the matching results.

Answer №3

Using the for .. in loop to iterate through either the keys or values of an array.

city = 'bangalore';
areas_array = {
  "bangalore": ['one', 'two'],
  "chennai": ['four', 'five'],
  "hyderabad": ['six', 'seven']
};

for (let key in areas_array) {
  if (key === city) { 
    // perform logic here
  } 
}

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

Determining the True Width of a Div

I am working with a div that has a class of myid_templates_editor_canvas-selection. <div class="myid_templates_editor_canvas-selection" style="position: absolute; font-size: 0px; left: 0px; top: 0px; width: 377px; height: 174px;"></div> The w ...

Avoid Conversion of HTML Entities in Table Cells

<table> <tr> <td>&gt;</td> </tr> <tr> <td>&&#xfeff;GT</td> </tr> </table> In the code snippet above, I have table cells containing HTML entities. A re ...

The mySql INSERT query in my Node application is not returning any results, even after using res.json()

I have recently delved into using Node.js and I am facing a bit of a challenge. Currently, I am attempting to insert a new product into my table. However, the ID for the product is not set to auto-increment. Therefore, in order to save the ID, I am implem ...

Different ways to call an ES6 class that is bundled in the <script> tag

Currently, I am utilizing Webpack to transpile my ES6 classes. Within the bundle, there is a Service class that can be imported by other bundled scripts. class Service { constructor() { // } someMethod(data) { // } } expo ...

When attempting to import * as firebase from 'firebase/app', the result is null

Recently, I've been encountering an issue while attempting to incorporate firebase v9 into my Next.js project. Every time I import it, it returns as undefined... import * as firebase from 'firebase/app' export function getFirebaseApp() { ...

Tips for saving data in a one-dimensional character pointer array

I am working on storing values into a character pointer pointer. Below is the code I have come up with: #include<string.h> #include<stdlib.h> #include<stdio.h> int count=0, index, total_stops; char *routes[10], *stops[10][10]; char *s ...

Troubleshooting HttpErrorResponse in an Angular App with PHP API

In my Angular application, I am utilizing Angular HttpClient along with PHP on the backend to handle data. However, I encountered an error while attempting to save data. Error Encountered: To connect to the database and pass data, I am using the database ...

Struggling to retrieve information from JSON using ReactJS

I am currently working with a JSON file called data.json { "link_template": "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit={num-results}&country={country-code}", "links": { "alternate": "http://www.rottentoma ...

Access control using Vue.js Cookies

Within my current project, we have both superusers and staff members. The specific task of deleting users is reserved for the superuser role only. This leads me to question whether it is plausible to delete a user by utilizing cookies? ...

Incorporating Typescript with Chart.js: The 'interaction.mode' types do not match between these two entities

I am working on developing a React Functional Component using Typescript that showcases a chart created with chartjs. The data and options are passed from the parent component to the child component responsible for rendering the line chart. During the pr ...

Determine the types of values for an object through the use of Generics

After spending a while pondering over this issue, I have yet to discover an elegant solution. My dilemma begins with an Enum: export enum Enum { A, B, C, } Next, there is an object that utilizes the Enum. While the structure is somewhat predi ...

Mocking a function from within the method under test

I need to run tests on a method in my code that runs a series of functions, one of which sends an email. Is there a way to prevent this function from sending emails during testing? I want to avoid using conditional statements like the one below in my cod ...

What is the process for sending a request to a static resource along with parameters?

I currently have a node.js restify server running, along with a folder containing static resources. const restify = require('restify') let server = restify.createServer() server.listen(8080, function () { console.log('%s listening at ...

Angular feature that enables the use of multiple filter values at once through pipes

Using *ngFor, buttons are dynamically generated to filter by different values. For example, if the key 'location' has values 'west' and 'england', buttons for both 'west' and 'england' will be available for ...

to convert a JSON string array into an object representation

{ "itemlist":{ "appid":"ST_UWL", "transid":"STAT_ID_7001", "overalltransstatus":"O", "translastmodifieddate":"04.FEB.2016 00:00:00", "requestor":{ "no":"296111", "name":"Sowmya Rao", "adid":"SO29" ...

Converting Cookies to Numeric Values in JavaScript: A Step-by-Step Guide

I'm currently developing a cookie clicker website and am encountering an issue with saving the user's score to localstorage when they click the "save" button. Here is what my code looks like: let score = 0; function addPoint() { score += 1; } ...

What makes the vue <template> is incorrect when using v-bind:src?

I'm facing a challenge in dynamically switching html content. I tried using vue-loader src to import, but v-bind:src doesn't seem to have any effect. <template src="./app.html"></template> It seems to be working fine here. <temp ...

Is it possible to merge various jQuery setTimeout functions together?

I am currently using the following jQuery code for a specific task: setTimeout(function() { $("#ToDo1").removeClass("fa-spin fa-spinner"); $("#ToDo1").addClass("fa-check-square"); $("li:first").html("<i class='fa-li fa fa-check-square& ...

Retrieve the parent object from the policy field type

Imagine you have a query that retrieves a list of products like the one below. query ProductList() { products() { name price stockQuantity isAvailable @client # This field exists only locally } } In addition, you've set up a type ...

Guide to sending JSON data through the Wufoo Entries API

It seems the current documentation is lacking in detailing the proper procedure for submitting forms via Ajax. Although there is The Entries POST API, it specifically discusses xml and lacks an example payload. Upon further investigation, I discovered Wuf ...