Combining one item from an Array Class into a new array using Typescript

I have an array class called DocumentItemSelection with the syntax:

new Array<DocumentItemSelection>
. My goal is to extract only the documentNumber class member and store it in another Array<string>, while keeping the same order intact.

Is there a more efficient way to achieve this in Javascript/Typescript? Currently, I'm using a for/foreach loop.

export class DocumentItemSelection {
  documentNumber: string;
  documentDate: Date;
  isCurrentOwnerFlag: boolean;
}

Answer №1

To simplify this task, you can utilize Array.prototype.map. If your array of type DocumentItemSelection is stored in a constant named data, you just need to ensure that the callback function returns the value from the key documentNumber:

const documentNumbers = data.map(datum => datum.documentNumber);

TypeScript will accurately deduce the type for the documentNumbers array without any issues - it will be typed as Array<string> (or string[]).

For a demo, check out the sample in the TypeScript playground.

Answer №2

If you want to achieve this, follow these steps :

export class AppComponent implements OnInit {
  datas = [
    {
      id:0,
      name: "first",
    },
    {
      id:1,
      name: "second",
    },
    {
      id:2,
      name: "third",
    },
  ];

  ngOnInit() {
    const arrayOfName = this.datas.map(item => item.name); // Implement it here
    console.log('arrayOfName', arrayOfName);
  }
}

The .map function will transform what you return, so just make sure to return the desired value.

You can also view a live example on Stackblitz by clicking here

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

Why is the button missing from the codepen?

I attempted to recreate the code from this Codepen link: https://codepen.io/jakaric/pen/mjJQvg However, unlike what you see here (in the run result), the liquid "Pretty little button" is not showing up in my local files. On Codepen, there is no library me ...

Converting data to a JSON string using jQuery's AJAX method

When I use document.write() for JSON data, it works fine outside of the AJAX call, but not inside the .done() function. I even tried removing the dataType: 'json' parameter, but it still didn't work. $.ajax({ url: "http://api.wundergrou ...

Change the websocket origin to localhost in a javascript setting

My server is hosting the domain example.com. Every time a user loads a page on this server, it utilizes a WebSocket client in JavaScript to connect to another WebSocket server. However, the other server has CORS enabled, which prevents the connection bec ...

Styling array of arrays

When retrieving data from an API, the structure looks like this: "key1" : { "subkey1" : value "subkey2" : value "subkey3" : value } "key2" : { &q ...

What are some ways to implement dangerouslySetInnerHTML in conjunction with read-more-react from npm?

Is there a way to include dangerouslySetInnerHTML in a text field without receiving an error? <ReadMoreReact text={yourTextHere} min={minimumLength} ideal={idealLength} max={maxLength} readMoreText={read ...

I possess a pair of arrays, and I aim to transfer certain elements from Array1 to Array2 while maintaining their references

Looking to implement two JavaScript arrays using AngularJS. My goal is to transfer elements from Ar1 to Ar2, and then have any changes made to the values in Ar2 automatically update the values in Ar1 as well. ...

Unable to transform data types

Currently, I am studying the JavaScript for automation session at WWDC. Here is an example taken from slide 99 that I am working on. On a fresh installation of Yosemite, I encountered an error on line 3. Safari = Application('Safari') doc = Safa ...

BufferGeometry: techniques for rendering face groupings

I have 2 different shapes and 2 sets of patterns. My primary objective is to sometimes hide a portion of the first shape (requiring 2 groups) while simultaneously displaying a section of the second shape (only needing 1 group). Prior to the r72 update, I u ...

Is the angular.cli still necessary when using an Angular ejected project?

Angular ng eject Once a project is ejected, is it still necessary to have an angular.cli file in the project? If so, which specific keys in the angular.cli remain useful? ...

Updating GridView row only if there are changes, the value remains unchanged in JavaScript. Disappointing

Incorporating a gridview (ASP.net) inside an update panel, I included a "Save" button that triggers a loop through all the rows of the grid view to pass data to a stored procedure for updating each row. However, this process proved to be slow and resulted ...

Refresh a div using jQuery and include PHP files for dynamic content updating

This is the code I am using to dynamically update divs containing PHP files: $(document).ready(function() { setInterval(function() { $('#ContentLeft').load('live_stats1.php').fadeIn("slow"); $('#ContentRight').load( ...

A guide to swapping text in a jQuery DOM component

In order to construct HTML from a jQuery ajax response, I prefer not to nest unsightly strings in javascript and avoid using templating scripts like mustache. Instead, I decided to utilize a template HTML with display: none as shown below: <div id="mes ...

How can I display actual images received as escaped string literals from ExpressJS?

Is there a way to transform this data from ExpressJS into an actual image? The information I'm receiving looks like this instead of an image: {`data: 'PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\ ...

Tips for enabling mouse functionality while utilizing PointerLockControls

I'm currently working on a 3D art gallery using Three.js and PointerLockControls for navigation. My goal is to have the artwork on the gallery walls clickable, triggering a pop-up window with additional information. However, it seems that PointerLock ...

unable to save the information to mongoDB

I've been attempting for the past 3 hours to save data from an HTML form to MongoDB using Node.js. When I click submit, it redirects to another page displaying the submitted data in JSON format, but it's not getting stored in the database. Here ...

The Clerk middleware is causing delays in loading, leading to a 504 Error on NextJS / Vercel with the message 'FUNCTION_INVOCATION_TIMEOUT'

I'm currently working on a web page where I need to utilize Clerk for authentication and login. However, I've encountered an issue with the middleware taking too long to load, causing deployment problems for the app. Here is the code from middle ...

Error: script 'start' is not defined on Heroku

Hello there! I'm currently working on deploying an application to Heroku from my GitHub repository. To ensure that everything runs smoothly, I made some modifications to the start script in the package.json file. Specifically, I adjusted it to point t ...

Is it possible to submit two forms simultaneously using jQuery or AJAX?

My plan is to save 2 forms, with the first form providing the Foreign key for the second form. This is my attempt at saving this using JavaScript: $("#btnSave").click(function (e) { e.preventDefault(); $('#workForm').submit(); ...

Include CakePHP named parameters in the URL when selecting from a list

If I have a selection list like the one below: <select name='languages'> <option value='german'>German</option> <option value='english'>English</option> </select> How can I use Jav ...

The issue with implementing simple getElementsByClassName JavaScript in the footer of a WordPress site persists

I am facing an issue with a 1-liner JavaScript code in the footer where getElementsByClassName function doesn't seem to work for tweaking style attributes. The text "Hello World" is displaying fine, so I suspect it might be a syntax error? Here' ...