Loop through a collection of elements of a certain kind and selectively transfer only certain items to a different collection of a different kind

When working with typescript, I am faced with the challenge of dealing with 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}
]

I am trying to figure out a way to loop through myFirstArray and assign all names as nicknames in mySecondArray. Is there a method to achieve this functionality?

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

Answer №1

If you only want to set a nickname, you can make the lastName field optional in the ISecond interface by using lastName?: string. The updated interface will look like this:

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

To assign the nickname value from each element of myFirstArray to mySecondArray, you can utilize the this.myFirstArray.map() method. Here's how you can do it:

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

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

Check out the working code on Stackblitz... (View console for output).

Answer №2

In this scenario, mySecondArray is defined as an array of type ISecond. Therefore, when assigning values to it, both properties of the object must be included.

For example -

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

Answer №3

Utilize the map function to transform your array:

this.peopleList = [
    {name: 'Alice', age: 25},
    {name: 'Bob', age: 35}
];
this.modifiedPeopleList = this.peopleList.map(({name, age})=> <IModified><any>{ 
    fullName: name,
    yearsOld: age
    });
console.log(this.modifiedPeopleList);

Answer №4

Make sure to properly set up your second array:

friends: IFriend[] = [];

Once initialized, populate it by iterating through the first array:

this.users.forEach((user: IUser) => {
    this.friends.push({username: user.name, lastName: ''});
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Chrome stack router outlet and the utilization of the Angular back button

I'm experiencing an issue with the back button on Chrome while using Angular 14. When I return to a previous page (URL), instead of deleting the current page components, it keeps adding more and more as I continue to press the back button (the deeper ...

Unleashing the Power of Typescript and SolidJS: Expanding the Properties of JSX Elements

Is there a way to enhance the props of an existing JSX element in SolidJS and craft a custom interface similar to the ButtonProps interface shown in this React example below? import Solid from 'solid-js'; interface ButtonProps extends Solid.Butt ...

The combination of Ace editor and Angular 2 leads to synchronization issues with Protractor

Currently, I am in the process of developing a new application using Angular 2 (version 2.0.0) and angular-cli (version 1.0.0-beta.14). In order to integrate Ace editor into my project, I have utilized an Angular 2 directive as per the guidelines provided ...

The input type '{}' does not match the expected type 'Readonly<IIdeasContainerProps>'. The property '...' is not found in the type '{}'

Having recently started using TypeScript, I'm encountering some issues when attempting to execute this code snippet. Error The error message reads as follows: Failed to compile 13,8): Type '{}' is not assignable to type 'Readonly &l ...

Angular 9: Subscribing triggering refreshing of the page

I've been working on an Angular 9 app that interacts with the Google Books API through requests. The issue I'm facing is that whenever the requestBookByISBN(isbn: string) function makes a .subscribe call, it triggers a page refresh which I' ...

Navigating with hashtags in Angular2 and anchors does not change the page position

I recently came across a helpful post that showed me how to append a fragment to the URL. Angular2 Routing with Hashtag to page anchor Although the fragment is successfully added, I'm encountering an issue where the page does not scroll to the speci ...

issue TS2322: The function returns a type of '() => string' which cannot be assigned to type 'string

I have recently started learning Angular 6. Below is the code I am currently working on: export class DateComponent implements OnInit { currentDate: string = new Date().toDateString; constructor() { } ngOnInit() { } } However, I am encounterin ...

Utilize key-value pairs to reference variables when importing as a namespace

Is it feasible to utilize a string for performing a lookup on an imported namespace, or am I approaching this the wrong way? Consider a file named my_file.ts with contents similar to: export const MyThing: CustomType = { propertyOne: "name", ...

displaying an item within a text field

I have an input box created using Angular reactive forms <input type="text" formControlName="OrgName" placeholder="Enter name" maxlength="60"> <p class="fieldRequired" *ngIf="showNameMSg" ...

Is hard coding permissions in the frontend considered an effective approach?

I'm in the process of creating an inventory management system that allows admin users to adjust permissions for other employees. Some permissions rely on others to function properly, and I need to display different names for certain permissions on the ...

Establish a public-facing link for a React component

After developing a React component that functions as a chatbot window, I am now looking for a way to make the opening button accessible across various websites and applications. My initial thought was to associate a URL with the button so that it can be ea ...

At what point does a vulnerability in a React or Angular library become a serious threat?

As a cybersecurity student, I have noticed numerous CVEs related to libraries used in React and Angular. One example is: │ Critical │ Prototype Pollution in minimist │ ├────────────── ...

What is the best way to access event.target as an object in Angular 2?

Apologies for my limited English proficiency. . I am trying to write code that will call myFunction() when the user clicks anywhere except on an element with the class .do-not-click-here. Here is the code I have written: document.addEventListener(' ...

Guide to separating the bytes of a number and placing them into an Uint8Array

I am looking to convert a JavaScript number into the smallest possible uint8array representation. For example : 65 535 = Uint8Array<[255,255]> (0b1111111111111111 = [0b11111111, 0b11111111]) 12 356 = Uint8Array<[48,68]> (0b0011000001000100 = [ ...

What is the best approach to integrating payment solutions into a React Native application running on version 0

Seeking advice on integrating payment systems in React Native 0.70. Previously utilized react-native-credit-card-input and react-native-credit-card-input-plus with earlier versions, but they are now incompatible. ...

Perform TypeScript type checks exclusively on a Next.js project

In my current project using Next.js with TypeScript in a mono-repo setup, I have multiple applications under the same repository. When pushing changes to this setup, various hooks are triggered locally to ensure that the modifications meet the required sta ...

Access a document and analyze its information

I am currently working with a file upload control that stores the selected file within it, as shown in the code snippet below: <div class="Block"> <label id="lbl">File </label> <input #fileInput type='file'/> </div ...

React with TypeScript presents an unusual "Unexpected token parsing error"

Recently, I encountered an issue with my helper function that was originally written in JavaScript and was functioning perfectly. However, as soon as I introduced TypeScript into the mix, strange behaviors started to surface. Here is the snippet of code fr ...

Struggling with TypeScript compilation in a Vue.js project? Encounter error code TS2352

Here is my code snippet from window.ts import Vue from 'vue' interface BrowserWindow extends Window { app: Vue } const browserWindow = window as BrowserWindow export default browserWindow Encountering a compilation error Error message: TS2 ...

What is the best way to pass form values from child components to parents when utilizing a value accessor implementation?

What is the most effective method to retrieve the values of a child component control group from a parent component? I have currently implemented this using value accessor, but I am curious about the best approach. You can check out the plunker demo I have ...