Iterate over an array of one type and copy only specific items in another array of another type

Viewed 86

In typescript, I have two arrays:

interface IFirst{
    name: string;
    age: number
}

interface ISecond {
    nickName: string;
    lastName: string;
}   

myFirstArray: IFirst[];
mySecondArray: ISecond[];

myFirstArray = [
    {name: 'tim', age: 20},
    {name: 'jim', age: 30}
]

How can I iterate through myFirstArray and set all names to nickNames in mySecondArray? Something like:

this.myFirstArray.forEach((element: IFirst) => {
        this.mySecondArray.push({nickName = element.name});
      })
4 Answers

If you want to assign only nickname, then you need to make lastname as optional in ISecond interface like lastName?: string and interface will be,

interface ISecond {
  nickName: string;
  lastName?: string;
}

You can use this.myFirstArray.map() method and assign nickname value as myFirstArray element name to this.mySecondArray like,

this.mySecondArray = this.myFirstArray.map((element: IFirst) => {
  return { nickName: element.name };
});

console.log("this.mySecondArray ", this.mySecondArray);

Working code in Stackblitz... (Take a look at console)..

Here you have mySecondArray is of type array ISecond. So whenever you want to assign values in it you should assign both properties of the object.

Like below -

this.myFirstArray.map((element: IFirst) => {
  this.mySecondArray.push({nickName = element.name, lastName: ''});
})

You can use map method:

this.myFirstArray = [
    {name: 'tim', age: 20},
    {name: 'jim', age: 30}
];
this.mySecondArray = this.myFirstArray.map(({name, age})=> <ISecond><any>{ 
    nickname: name,
    lastName: ''
    });
console.log(this.mySecondArray);

You should initialize second array:

mySecondArray: ISecond[] = [];

and then push elements:

this.myFirstArray.forEach((element: IFirst) => {
    this.mySecondArray.push({nickName: element.name, lastName: ''});
})
Related