0
votes

I have two arrays like one is City and another is Zipcode

cities=[{name:"aaa"},{name:"bbb"},{name:"ccc"},{name:"ddd"}]
  zipcode=[{num:"111"},{num:"222"},{num:"333"},{num:"444"}]

How to link up two arrays. If i use two forloops, then cities and zipcode becomes twice. Can anyone please help I am expecting output like this aaa-111 bbb-222 ccc-333 ddd-444

But i am not getting expected result. I tried this. linkup array of data stackblitz

2
Why can't you just do it in the component? (typescript file) - Jamie Rees
This is a big design smell. Don't use parallel arrays. use a single arrays of objects, where each object has a city name and a zip code. I these arrays come from two different places, then use your TypeScript code to combine them into a single array of objects. A component is not just a view. It's also a TypeScript class, where you can write TypeScript code. - JB Nizet
I tried in ts file also using mapping,but i am not getting - PRUDHVI RAJ
What have you tried then? - JB Nizet
i agree with @JBNizet .. you should not have parallel arrays - programoholic

2 Answers

2
votes

Change your html like this

<li *ngFor="let x of cities;let i=index">
     <div class="form-group" (click)="City(x)">
        <label>{{x.name}}-{{zipcode[i].num}}</label>
     </div>              
</li>

Use the index of the cities array to target the corresponding zipcode array's element. But for this to work you need to ensure that the 2 arrays are of same length and have same index refering to same values in both of the arrays

See updated stackblitz

OR

You can combine the 2 arrays in ngOnInit method using map like shown below.

ngOnInit () {        
    this.cities.map((x:any, i) => x.num = this.zipcode[i].num);
  }

Then use in html like

<div class="form-group" (click)="City(x)">
  <label>{{x.name}}-{{x.num}}</label>
</div>  
0
votes

Since you already have the index, why not simply use zipcode[i].num

Something like this:

<div class="admin-page">
  <div class="row">
    <div class="col-md-12">
      <div class="row">
        <div class="co col-md-12">
          <li *ngFor="let x of cities;let i=index">
            <div class="form-group" (click)="City(x)">
              <label>{{x.name}}-{{zipcode[i].num}}</label>
            </div>
          </li>
        </div>
      </div>
    </div>
  </div>
</div>

Here's an Updated Working Sample StackBlitz for your ref.