【问题标题】:Finding objects within objects在对象中查找对象
【发布时间】:2022-01-09 13:20:32
【问题描述】:

我正在尝试在对象数组中搜索以查看是否有任何对象包含我要查找的对象并将其分配给变量。

这是我正在使用的界面。基本上我有一系列国家,每个国家都有自己的城市。

import { ICity } from "./city";

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

我要找的对象是这个函数的city参数,但它总是返回undefined。查找某个城市所属国家/地区的最佳方法是什么?

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

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

(在我看来)最好的方法是将国家/地区 ID 存储在城市中,这样您就可以更轻松地找到它。

但在这种情况下,您可以像下面这样:

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);
}

【讨论】:

  • 这与 OP 的当前代码没有什么不同,并假设 city 是一个字符串
  • 这有很大不同,因为数组不支持包含
  • 你只是教我一些东西。谢谢老兄。
【解决方案2】:

您的 ICity 类型对象不只是我假设的一个简单字符串,所以检查如下:

if (cn.majorCities.includes(city)) 

如果majorCities 元素之一 是通过city 变量引用的实际实例,则只会返回true。

因为您的 ICity 界面肯定包含类似 name 属性的东西 例如

interface ICity {
name: string
}

你应该检查这样一个字符串类型的属性。

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

    })) {
    // do something
}

【讨论】:

    【解决方案3】:

    你应该像下面那样做

    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 founded!')
    
      })
    }
    findCity('Shiraz')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-05
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多