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

What is the best way to dynamically import two css frameworks in React?

Currently, I am involved in a project that requires me to incorporate a button for toggling between Bootstrap and Foundation at the request of my client. After exploring several alternatives, I have determined that utilizing hooks to manage the state of e ...

The import of type cannot be done within paths in tsconfig

Currently, I am tackling a server side project utilizing TypeScript. In this context, I have established various types in ooo.d.ts and configured the paths within tsconfig.json. However, upon attempting to import the specified type, an error is being displ ...

Combining arrays in JSON with the power of Groovy 2.4

Below is the JSON input I have, where I am attempting to merge scheduleDetails with the same ID: {"orderLines": [{ "ID": "001", "scheduleDetails": [{ "address": { ...

Guide on incorporating a range object into a VBA function to produce an array output

I'm running into an issue with my code where a procedure that generates cell ranges based on specific criteria is causing problems when I try to call a function that takes a cell range object as input and returns an array. The error message I keep rec ...

Using type definitions in non-TS files with VSCode: A beginner's guide

My code is not in TypeScript, shown here: // foo.js module.exports = app => { // some logic here } I want to enhance my development experience by using TypeScript definition files to specify the type of the argument app, enabling VSCode to provide ...

The specific property 'splice' cannot be found within type 'T'

As I delve into working with TypeScript, an unexpected error arises: Property 'splice' does not exist on type 'T'. type Item = { name: string, body: string, imgOne: string, imgTwo: string, }[] // Another file contains this func ...

Including elements into an array encoded in JSON

After coming across a solution on stackoverflow, I implemented a method to encode my MYSQL output into a JSON encoded array. $sth = mysql_query("SELECT ..."); $rows = array(); while($r = mysql_fetch_assoc($sth)) { $rows[] = $r; } print json_encode( ...

What is the best way to send multiple parameters to @Directives or @Components in Angular using TypeScript?

I am facing some confusion after creating @Directive as SelectableDirective. Specifically, I am unclear on how to pass multiple values to the custom directive. Despite my extensive search efforts, I have been unable to find a suitable solution using Angula ...

What is the best way to organize values within an array in PHP?

Here's the scenario with the variable $result: [result] => Array ( [Jeffrey] => Array ( [date] => Array ( [0] => 1294439732 [1] =& ...

The JSX component cannot be named 'Stack.Navigator' or used as such

Encountering a type issue with react navigation using Stack.Navigation or Stack.Group from createNativeStackNavigator The error message indicates that the types do not match with JSX.element. Specifically, it states: Type '{}' is not assignable ...

Learning how to smoothly navigate to the top of a page when changing routes in Angular using provideRouter

Is there a way to make the Angular router automatically scroll to the top of the page when the route changes? In my previous setup using NgModules, I could achieve this with: RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'top' }) ...

Angular - Reacting to dynamically rendered content post-navigation

I am working on an angular application that consists of various components and pages where users can create and view html content. Once the content is fully loaded, I need to search for specific elements and add an onclick event to them. My initial approa ...

Using Ionic2 to connect with PHP server APIs

I am fairly new to working with ionic, although I have a basic understanding of angular2. My goal is to access an API created in PHP using the combination of ionic2 and angular2. feed.php header('Access-Control-Allow-Origin: *'); $db_ ...

Angular Error TS2554: Received x arguments instead of the expected 0 on piped operators

I encountered an issue with Error TS2554: Expected 0 arguments, but got 4 when dealing with the observable getHappyDays(). The getHappyDays() Observable returns either Observable<HttpResponse<IHappyDays>> or Observable<HttpErrorResponse> ...

Having trouble getting the installed datejs typings to work properly

As I delve into Typescript due to my interest in Angular 2, I have come across the datejs Javascript library. To incorporate it into my Angular 2 project, I went ahead and installed datejs via npm, ensuring that it is correctly listed in my package.json. A ...

Encountered an issue when attempting to send data using this.http.post in Angular from the client's perspective

Attempting to transfer data to a MySQL database using Angular on the client-side and Express JS on the server-side. The post function on the server side works when tested with Postman. Here is the code snippet: app.use(bodyParser.json()); app.use(bodyPa ...

Angular2 app fails to update after emitting an event

I need help with a child component responsible for updating phone numbers on a webpage. The goal is for the application to automatically display the changed phone number once the user hits the 'save' button. Here's a visual of how the appli ...

Retrieve predefined values from a TypeScript controller in Stimulus using the default Symfony configurations

Currently, I am delving into the realm of Stimulus using a standard Symfony6 and Encore setup, with the only notable difference being my use of Typescript. As per the guidance in the Stimulus documentation, typed values should be utilized in the following ...

Filling a data entry with simultaneous commitments

Sample code: type Alphabet = 'a' | 'b' | 'c'; const alphabetMap: Record<Alphabet, null> = { 'a': null, 'b': null, 'c': null} // Select any asynchronous processing function you prefer funct ...

Looking for the closest latitude and longitude values in a multi-dimensional array

I am facing a challenging task of searching through a multi-dimensional array to find the closest match based on lat and lon values and return that sub-array. Let's say I have the following preset values: Lat=50.6000, Lon=-74.15000 I need to search ...