0

i have two array

 firstArray= [{id: 1, name:'firstValue1'}, {id:2, name:'firstValue2'}]

 secondArray= [{ "num": 1, "fullName": SecondValue1 , id:1}]

i want to show data like this

firstValue1 -------->> SecondValue1

firstValue2 -------->> 

How can i populate this two array in [(ngModel)] or input or select box?

Thankyou for your time and response!

2 Answers 2

1

Instead of maintaining secondArray as Array convert it to HashMap

Example

firstArray = [
    { id: 1, name:'firstValue1' }, 
    { id: 2, name:'firstValue2' }
];
secondArray = { 
    '1': { "num": 1, "fullName": "SecondValue1", id: 1 },
    '2': { "num": 1, "fullName": "SecondValue2", id: 2 },
}

html

<div *ngFor="let item of firstArray">
    <p>{{item.name}} --> {{secondArray[item.id]?.fullName}}</p>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

If you don't want to add an index manually to your secondArray, give this a try:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  firstArray = [
    { id: 1, name: 'firstValue1' },
    { id: 2, name: 'firstValue2' }
  ];

  secondArray = [
    { "num": 1, "fullName": 'SecondValue1', id: 1 },
    { "num": 2, "fullName": 'SecondValue2', id: 2 }
  ];

  getSecondArrayItem(id) {
    return this.secondArray.find(item => item.id === id);
  }
}

And in the template:

<div *ngFor="let item of firstArray">
    <p>{{item.name}} --> {{ getSecondArrayItem(item.id)?.fullName }}</p>
</div>

Here's a Working Sample StackBlitz for your ref.

3 Comments

Sidd, Your code works, but if the function is more complex, It's better create an auxiliar array because getSeconArrayItem are executed several, several several times along live of component
Can you please elaborate as to what exactly do you mean by How can i populate this two array in [(ngModel)] or input or select box?

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.