Как сопоставить массив в угловых - PullRequest
0 голосов
/ 01 ноября 2018

Друзья, пожалуйста, помогите мне с этим, поскольку я новичок в angular и машинописи

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

Ответы [ 3 ]

0 голосов
/ 01 ноября 2018

Используйте 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
  } 
}
0 голосов
/ 01 ноября 2018

Цикл и проверка с ключом:

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

0 голосов
/ 01 ноября 2018
Object.keys(areas_array).filter(key=> key===city).map(match=> areas_array[match]);
...