【问题标题】:How to match array in angular如何以角度匹配数组
【发布时间】:2019-04-05 12:26:11
【问题描述】:

朋友们请帮我解决这个问题,因为我是 angular 和 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
}

我想在 area_array 中获取与城市匹配的数组。格式化area_array是正确的方法吗

【问题讨论】:

  • 您的代码没有多大意义。你想做什么? areas_array 是什么?
  • 你能补充更多细节吗?另外,为什么areas 是一个有 1 个对象的数组?
  • 如果你想选择那个bangalore区域,你可以这样做:this.area = this.areas[0][city](不知道你为什么把那个字典包裹在数组中......)
  • 也许你是对的@ShivKumarBaghel,但我个人认为我们不应该根据 我们个人 认为 OP 想说的话来编辑帖子(尤其是代码部分) .那只是我。 :)
  • 不是“只有你”:]

标签: javascript arrays angular typescript filter


【解决方案1】:
Object.keys(areas_array).filter(key=> key===city).map(match=> areas_array[match]);

【讨论】:

    【解决方案2】:

    使用for .. in 迭代数组键或值。

    city = 'bangalore';
    areas_array = {
      "bangalore": ['one', 'two'],
      "chennai": ['four', 'five'],
      "hyderabad": ['six', 'seven']
    };
    
    for (let key in areas_array) {
      if (key === city) { 
        // logic
      } 
    }
    

    【讨论】:

    • 请添加一些解释。
    【解决方案3】:

    循环并用键检查:

    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 serchCity = 'bangalore';
        for (let key in this.areas_array) {
          if (key === serchCity) {
            console.log(this.areas_array[serchCity]);
          }
        }
      }
    
    }
    

    参考:https://stackblitz.com/edit/angular-qjndzg?file=src%2Fapp%2Fapp.component.ts

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 1970-01-01
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      相关资源
      最近更新 更多