How do I extract a specific property from an array of objects and assign it to a new array in Typescript 2?

I've got this TypeScript 2 "model" that looks like this:

export class MyModel {
   myProperty1: string;
   myProperty2: string;
   ...
}

In addition to the model, I have another class defined as follows:

// Imports excluded for brevity
@Component
...
export class MyClass {
   private myArray: Array<MyModel>;

   ngOnInit() {
      this.myArray = ...// a service call populates the array with MyModel objects;
   }

   ngAfterViewInit() {
      var newArray: Array<string> = this.myArray ??? // extract only myProperty1 from objects in myArray and assign them to newArray
   }
}

How can I extract just the myProperty1 values from myArray and populate a new array of strings?

For instance, if myArray contains two MyModel elements like below:

[{"one", "apple"}, {"two", "oranges"}]

The resulting newArray should contain these two string elements:

["one", "two"]

Answer №1

Utilize the map() method to achieve this. The map function iterates through each item in the given array and returns a new array containing specific properties, as chosen by you. In my instance, it creates an array solely based on the prop1.

const arrays = [{prop1: "one", prop2: "apple"}, { prop1: "two", prop2: "oranges"}];

const newArr = arrays.map(item => item.prop1);
console.log(newArr);
   

Answer №2

Consider using Array.map method, which generates a fresh array by iterating through each element.

this.newArray = myArray.map(item => item.property)

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

Advice for transferring a Java variable to another JSP page with embedded JavaScript code

This is a snippet of my Java class: @RequestMapping(value = "/front", method = RequestMethod.GET) public String oneMethod(@RequestParam String name, Model model) { String str = "something"; model.addAttribute("str", str); return "jsppage"; } ...

What is the process for initiating printing in a separate window?

Is there a way to modify the code below so that when I click "Print" it opens in a new window instead of redirecting and losing the original receipt? <div class="print_img"> <button onclick="myFunction()"> <div align="justify ...

What is the process for NPM to execute a command that is not located in the path directory?

When I try to run the ava command from my project directory that contains AVA tests, I encounter an issue because it is not in my path. In my project, the npm test command is configured as ava tests/*.js --verbose, and mysteriously manages to execute the ...

Having trouble with JQuery Ajax when trying to send multiple data at once?

name = "John Doe"; username = "johndoe123"; password = "secure123"; $.ajax({ type: 'POST', url: "https://example.com/api", data: { name: name, username: username, password: password }, success: function(response, status, xhr ...

The issue of TypeError arising while invoking a method within TypeScript Class Inheritance

Currently, I am developing a Node.js application with TypeScript. In this project, I have a base controller class named BaseController and a derived controller called SettingController. The intention is for the SettingController to utilize methods from the ...

What type will the click handler return be determined by TypeScript?

I am working on a custom button control that has a click handler which can either return a promise or void. Here is an example of the button options interface and the click handler: // --- Options for button control export interface buttonOptions { aPr ...

The error message "Vuex-persist encounters an Uncaught TypeError: s is not a function" is

Can someone help me with this code issue? Here it is: I'm not sure what the exact problem is, but maybe someone can point me in the right direction! const vuexLocal = new window.VuexPersistence.VuexPersistence({ storage: window.localStorage, }); con ...

The Angular application has been successfully deployed on a Tomcat server as a war

I am planning to deploy a single page application (SPA) developed in Angular, along with various static files like *.css, .js, /assets/, all packed inside a war file on Tomcat. The issue I am facing is that whenever a user enters a path that does not corr ...

Declaring a custom Angular Pipe

I've created a custom Pipe to filter a list of items and integrate it into my Angular/Ionic application. // pipes/my-custom-filter/my-custom-filter.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'myCustomFilt ...

Trouble with ng-repeat when working with nested json data

Check out this app demo: http://jsfiddle.net/TR4WC/2/ I feel like I might be overlooking something. I had to loop twice to access the 2nd array. <li ng-repeat="order in orders"> <span ng-repeat="sales in order.sales> {{sales.sales ...

Fetching data from one component to load an Angular component

Essentially, I have a grid within Ionic that dynamically populates its rows using ngFor. Each row contains an ionic button labeled "View details" which, when clicked, should display all the data associated with that specific object. Imagine it as a preview ...

What could be causing the issue with dayjs dynamic importing in TypeScript?

Currently, I am developing a web screen within a .NET application and facing an issue with sending datetime preferences from the system to the web screen using CefSharp settings. AcceptLanguageList = CultureInfo.CurrentUICulture.Name In my TypeScript code ...

There is an issue with GraphView's GraphViewSeries being null

Why is my GraphViewSeries always null even though I have values in my GraphViewData? Take a look at my code snippet below: GraphViewData[] graphViewData = new GraphViewData[1000]; for (int i = 0; i < listprice.size(); i++) { Log.e( ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

Best practices for utilizing child component methods within a parent component in VUE

I am working with the ImageUpload.vue component, which is a straightforward Bootstrap modal containing a few methods. I am currently exploring the best approach to utilize one of these methods. Could it be implemented like this: const app = new Vue({ ...

What is the designated destination for JWT Tokens?

For my user login/signup process, I'm utilizing JWT and have a query regarding how the token is transmitted. At present, I am saving the token as a property in a JSON object on the server side, then passing it to the front-end. Upon receiving the obj ...

Troubleshooting problem with event triggering in Angular's ngSelect dropdown menu items

Hello, I am currently utilizing ngSelect but encountering an issue. Whenever a user hovers over an option in ngSelection, I would like to trigger an event that is created in my typescript file. I am using Angular 13, so I am unsure how to achieve this. Is ...

Parsing values from deeply nested objects and arrays

I've come across this issue before, but I'm having difficulty navigating through a nested structure. I can't seem to find any guidance in the right direction. Here is the object I'm attempting to parse: const nestedArray = { id ...

Determine if a JavaScript code in my ASP view will be executed based on control from the controller

Working on an ASP.NET MVC4 system, I have a javascript code that displays a performance graph of students when the page loads. Here is the code for the graph: <script> window.onload = function () { var r = Raphael("holder"), ...

Discover the secret to smoothly scrolling to an element in ReactJs

Currently, I am in the process of constructing a Single Page Application (SPA) using React and one key functionality I need to implement is navigation that scrolls to specific sections on the page when clicked. This behavior is similar to how anchor tags w ...