【问题标题】:Angular 2 TypeScript distinct filtering nested dataAngular 2 TypeScript 不同的过滤嵌套数据
【发布时间】:2017-08-10 09:40:43
【问题描述】:

我想知道如何在 TypeScript 中过滤嵌套数据并获得不同的值。

我正在尝试获取国家/地区名称:long_name 作为不同的值,其中 types[0] == "country"

我可以编写 3 个 For 循环和 2 个 If 语句,但我不知道如何通过 .filter().find() 以更简单的方式做到这一点,有人可以帮我吗?

我需要一个LINQ alike 语句来选择types[0] == "country" 所在的所有国家/地区名称 (long_name)。

这是数据:

这是我的代码:

getAllCountries(): Observable<any[]> {
    return this.getAll()
            .map((countries: any[]) => countries.filter(c => c.address_components.some(nestedObj => nestedObj.types.indexOf("country") >= 0)));
}

我现在得到的是所有通过过滤条件的对象。我现在需要将这些国家/地区名称 (long_name) 抓取/映射到不同的数组。

【问题讨论】:

  • Unique values in an array的可能重复
  • @jonrsharpe 我可能很愚蠢,但这无济于事。感谢您的努力和投票。
  • 那我不明白你在问什么,难道不是为了不同/独特的国家名称吗?你能给出一个带有预期输出的 JSON 的实际文本样本吗?您当前的代码输出了什么,它与期望的结果有何不同?
  • @jonrsharpe 我需要的确实是一个带有国家名称的 DISTINCT 数组。就像您可以在嵌套数据中进行 LINQ 过滤一样。我不知道如何select 国家名称where 深层嵌套属性types[0] 等于“国家”。`
  • 订阅数据时应该这样做

标签: json typescript nested filtering


【解决方案1】:

如果您想要从每个条目中获取的只是 long_name 值,您可以按如下方式提取它们:

let long_names = countries
  .map(country => country.address_components.filter(component => component.types.indexOf('country') > -1)  // get relevant components
  .filter(components => components.length > 0)  // filter out any without a country component
  .map(components => components[0].long_name);  // get long name of first country component

然后您可以应用来自Unique values in an array 的解决方案来获取唯一值。

【讨论】:

    【解决方案2】:

    使用 lodash 的更简单方法是:

    countries=[];
    let data = _.find(countries, { types : ['country'] });
    countries= _.uniq(countries.push((data.long_name ? data.long_name : ''))) ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 2019-07-27
      • 2017-03-02
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多