0

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

6
  • 1
    Why can't you just do it in the component? (typescript file) Commented Mar 22, 2019 at 10:45
  • 1
    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. Commented Mar 22, 2019 at 10:47
  • I tried in ts file also using mapping,but i am not getting Commented Mar 22, 2019 at 10:48
  • What have you tried then? Commented Mar 22, 2019 at 10:53
  • i agree with @JBNizet .. you should not have parallel arrays Commented Mar 22, 2019 at 10:56

2 Answers 2

2

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>  
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.