Discovering items located within other items

I am currently attempting to search through an object array in order to find any objects that contain the specific object I am seeking. Once found, I want to assign it to a variable.

The interface being used is for an array of countries, each containing its own array of cities.

import { ICity } from "./city";

export interface ICountry {
    name: string,
    capital: string,
    language: string,
    population: number,
    density: number,
    area: number,
    majorCities: ICity[]
}

The city parameter in this function is what I am searching for, but it always returns undefined. What would be the most effective method to locate the country to which a given city belongs?

remove(city: ICity): void {
    var country;
    this.countries.forEach(cn => {
      if (cn.majorCities.includes(city)) {
        country = cn;
        console.log(cn);
      }
    });
    console.log(country);
  }

Answer №1

In my perspective, the most effective approach is to include the country id in the city data for easier reference.

Alternatively, you could implement it as shown below:

remove(city: ICity): void {
  var country;
  this.countries.forEach((cn) => {
    if (cn.majorCities.find(c => c.toLowerCase() === city.toLowerCase())) {
      country = cn;
      console.log(cn);
    }
  });
  console.log(country);
}

Answer №2

It's important to remember that your ICity type object is not just a simple string; therefore, a straightforward check like the following:

if (cn.majorCities.includes(city)) 

will only return true if one of the elements in majorCities matches the instance referenced by the city variable.

Since the ICity interface likely includes a property like name, such as:

interface ICity {
name: string
}

you should be checking for a string-type property like this:

if (cn.majorCities.some((el) => {
        return el.name == city.name

    })) {
    // do something
}

Answer №3

One potential solution is shown below:

const countries = [{
    name: 'Iran',
    cities: ['Shiraz', 'Tehran']
  },
  {
    name: 'Germay',
    cities: ['Berlin']
  }
]

const findCity = (city) => {
  countries.forEach(country => {
    if (country.cities.includes(city))
      console.log(city, 'has been found!')

  })
}
findCity('Shiraz')

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

Mongoose: When encountering a duplicate key error (E11000), consider altering the type of return message for better error handling

When trying to insert a duplicate key in the collection, an error message similar to E11000 duplicate key error collection ... is returned. If one of the attributes is set as unique: true, it is possible to customize this error message like so: {error: ...

Obtaining text from a select list using JQuery instead of retrieving the value

How can I retrieve the value from a select list using jQuery, as it seems to be returning the text within the options instead? Below is my simple code snippet: <select id="myselect"> <option selected="selected">All</option> <op ...

Button will be disabled unless a value is selected in the dropdown menu

I am currently dealing with a code issue where the button is disabled on page load when the dropdown value is empty. However, even after selecting a value from the populated database dropdown, the button remains disabled. Jquery: <script> $(doc ...

The controller and node js request associated are invisible to my HTML page

Here is my HTML code. I have just created a unique controller for a specific part of the code. <div class="mdl-grid" ng-controller="ValueController"> <div class="mdl-card mdl-shadow--4dp mdl-cell--12-col"> <div class ...

Working with arrays in Angular 4 to include new items

I am struggling with the code below: export class FormComponent implements OnInit { name: string; empoloyeeID : number; empList: Array<{name: string, empoloyeeID: number}> = []; constructor() { } ngOnInit() { } onEmpCreate(){ conso ...

Guide to storing a variable value when a user clicks on the client-side in a Grid View:

How can I store data in a variable on client click within a grid view? I have a Stored Procedure that returns Service Id based on the Department code provided. We are binding these details to a Grid View. How can we bind the Service Id to a variable that ...

Tips for incorporating fading text and a CTA into your content block

I am looking to protect the full content of my blog posts and allow access only to subscribed members. I want readers to see just a glimpse of the article before it disappears, prompting them to take action with a Call to Action (CTA) like in the fading te ...

Tips for preventing the extraction of resolve from promises and initiating a process before a callback

There is a common pattern I frequently find myself using: const foo = () => { const _resolve; const promise = new Promise(resolve => _resolve = resolve); myAsyncCall(_resolve); return (dataWeDontHaveYet) => promise.then(cb => c ...

Maintain consistent spacing after receiving a value

I have a content editable span where you can write whatever you want. For example: Hello, My name is Ari. However, when I try to retrieve the text and alert it using my program, it displays without any line breaks or spacing like this: "Hello,My name is ...

Is it possible for FormArray to return null?

Hello there. I've attempted various methods, but none of them seem to be effective. Currently, I am working on this task where I need to start a formArray for emails. email: [testestest] However, what I have is: email: [testestest] I'm encoun ...

Guide on converting JSON encoded data into a JavaScript array

I have a few web pages that display results in the following format: [{"id":"1","company":"Gaurishankar","bus_no":"JHA 12 KH 1230"}, {"id":"2","company":"Gaurishankar","bus_no":"BA 2 KH 2270"}] Now, I want to take this JSON encoded data and use it in a J ...

JavaScript incorporates input range sliding, causing a freeze when the mouse slides rapidly

Currently working on a custom slider and encountering an issue. When quickly moving the mouse outside the slider's range horizontally, exceeding its width, the slider doesn't smoothly transition to minimum or maximum values. Instead, there seems ...

I'm looking for a way to incorporate JavaScript code within an iframe tag. Specifically, I'm attempting to embed code into a Wix website using the "Embed HTML

Trying to execute the code below on a Wix website using "Embed HTML", but IFRAME is blocking scripts. Seeking help to embed custom HTML with JavaScript on platforms like Wix.com or Wordpress.com, as the embedded code is not functioning due to IFRAME restri ...

After the upgrade from Angular 5.2 to Angular 6, Bootstrap 4 dropdown and Bootstrap-select dropdown seem to have lost their dropdown functionality. This issue arose after updating to Bootstrap 4 and jquery

Update: Upon further investigation, I experimented with a standard Bootstrap 4 dropdown and encountered the same issue – it would not open. This leads me to believe that the problem may not be specific to the selectpicker class or the bootstrap-select de ...

Error Styling: Using CSS to Highlight Invalid Checkboxes within a Group

Is there a way to create a bordered red box around checkboxes that are required but not selected? Here is the code I currently have: <div class="fb-checkbox-group form-group field-checkbox-group-1500575975893"> <label for="checkbox-group-15005 ...

Develop a TypeScript class that includes only a single calculated attribute

Is it advisable to create a class solely for one computed property as a key in order to manage the JSON response? I am faced with an issue where I need to create a blog post. There are 3 variations to choose from: A) Blog Post EN B) Blog Post GER C) Bl ...

Compilation error in VueJS: missing dependency detected

I am facing an issue in my VueJS project where a file I am referencing seems to be causing a compilation error. Despite being present in the node_modules directory, the dependency is declared as not found. In the image on the left, you can see the directo ...

Acquire Content using jQuery and Navigate page horizontally

I am trying to achieve a unique effect by capturing content x and horizontally scrolling the page while the mouse is in motion, similar to swiping on a tablet. It seems simple enough.. Capture clientX on mousedown, ScrollLeft by ClientX while moving, Di ...

Playing out the REST endpoint in ExpressJS simulation

Suppose I have set up the following endpoints in my ExpressJS configuration file server.js: // Generic app.post('/mycontext/:_version/:_controller/:_file', (req, res) => { const {_version,_controller,_file} = req.params; const ...

Transmit an Array using Ajax and retrieve it on an ASP Classic page

I am facing a challenge where I need to pass an array using AJAX on an ASP page. After trying to send it as GET method and checking the data being received, I noticed that only the LAST record of the array is being processed by ASP. How can I successfu ...