Retrieving a collection of property values from an array of objects in TypeScript

class DataModel{
    constructor(private Name: string, private Id: number, private isAlive: boolean){}

    array1?: string[];
}

Picture this scenario: the array has been filled with information retrieved from an API call. Now, I have an array of DataModel instances. What I aim to do next is gather all the Names from these objects into a separate array. Unfortunately, I haven't come across a TypeScript solution for this particular issue.

Answer №1

Typescript can be considered an extension of javascript. Solutions that work for Javascript also work for Typescript.

const result = data.map( element => element.title );

Answer №3

  const originalData = [
        {"first":"Gretchen","last":"Kuphal","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f283d2a2a21382023297a7b0f28222e2623612c2022">[email protected]</a>","address":"416 
                            Lesch Road","created":"March 1, 2012","balance":"$9,782.26"}];

1. Simply copying the array:

const duplicateData = [...originalData];

  1. If you want all values, loop through them
  2. To access a single value, you can do this:

alert(duplicateData[0].first);

console.log(duplicateData[0].first);

You can also perform edits like below

const originalData = [
  {"first":"Gretchen","last":"Kuphal","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcdbced9d9d2cbd3d0da8988fcdbd1ddd5d092dfd3d1">[email protected]</a>","address":"416 Lesch Road","created":"March 1, 2012","balance":"$9,782.26"},
{"first":"Morton","last":"Mayer","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdbeaca1a0a2a3bebcb8a4bfbfa8a1fff88daaa0aca4a1e3aea2a0">[email protected]</a>","address":"1602 Bernhard Parkway","created":"April 29, 2017","balance":"$6,596.11"},
{"first":"Catalina","last":"Daugherty","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2467455045484d4a450a604551434c4156505d64424d484b49414a450a4a454941">[email protected]</a>","address":"11893 Kali Vista","created":"October 16, 2008","balance":"$6,372.86"},
{"first":"Orpha","last":"Heaney","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d69686f6c6872746e786a72717b2f2f5d7a707c7471337e7270">[email protected]</a>","address":"8090 Chris Stream","created":"November 21, 2015","balance":"$9,596.26"},
{"first":"Reva","last":"Mohr","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a487f6c7b34577572685a757e7b34747f6e">[email protected]</a>","address":"0291 Kailyn Stravenue","created":"November 6, 2014","balance":"$4,768.37"},
{"first":"Loma","last":"Keeling","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2551505754504a4c5640424c5744434340151c654248444c490b464a48">[email protected]</a>","address":"84460 Samson Knoll","created":"June 13, 2017","balance":"$9,361.16"}
];

const duplicateData = []; 

for (let obj of originalData) {
    duplicateData.push(obj.first);
}
// print
for (let name of duplicateData) {
    console.log(name);
}

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

Ways to verify the existence of empty arrays in an Object using underscore.js or jQuery

Is there a more efficient method to determine whether an object contains empty arrays (0-*) aside from the following approach: emptyArr: function() { var obj = getObj(); return obj.abc.length == 0 || obj.def.length == 0 || obj.ghi.length = ...

Utilizing Google Closure Library with Angular 6

I am looking to integrate the google closure library into my angular 6 application. To achieve this, I have utilized the following commands: npm install google-closure-compiler and npm install google-closure-library. My application can be successfully co ...

Changing an Array of DaysOfWeek to an Enum: A Simple Guide

I am receiving a WeeklyPattern with DaysOfTheWeek from EWS. It is stored in an Array and can include one day or multiple days. There is an Enum called DayOfWeekMask that I need to use to convert the Array values into the Enum format. If the WeeklyPattern ...

The Mat Dialog fails to launch in a popup window

I've encountered an issue with the Mat-Dialog where it opens up on the left side of the page instead of centered. I made sure to follow the steps outlined on the official Angular Material website here TS import { MatDialog } from '@angular/mate ...

Having difficulties creating an array due to identical id tags causing HTML to break in JavaScript

I've been grappling with this issue all day. Before delving into dynamic solutions, I'd like to create multiple divs with unique id tags or classnames rather than repeating ids. Whichever option proves simpler would be greatly appreciated. Curren ...

Deciphering a JSON array in PHP

After retrieving a decoded JSON array from the Facebook API, here is how it looks when printed: $Myposts = json_decode($response->getBody()); var_dump($Myposts); It displays various messages with their corresponding created times and IDs. Now, I want ...

The NullInjector has issued an error regarding the lack of a provider for the Decimal

I recently integrated lazy loading into my application. However, one of my services is in need of the DecimalPipe. The structure of my modules goes like this: service -> shared module -> App module To give you more context, I have already added "Co ...

Finding common elements between two arrays through partial matching

Imagine I have two arrays: var array_full = ['table', 'sleeping', 'data']; var array_part = ['sleep', 'able']; My goal is to extract items from the full string array (array_full) that do not contain any e ...

Unleash the power of drag-and-drop functionality with cdkDrop

I am currently tackling a project that requires the implementation of a drop zone functionality where elements can be dragged from a list and dropped in a zone for free movement. I intend to utilize a cdkDropList for the zone due to its comprehensive list ...

What is the best way to create an array in VBA that includes all the sheets in my workbook?

I have implemented the code provided by the spreadsheet guru to mass protect/unprotect my sheets. This file is regularly updated by me and utilized by other team members. My goal is to have certain cells open for editing while others remain restricted when ...

By utilizing Angular's @output decorator, data can be passed from child components to their parent counterparts

I have a situation where I am passing data from a child component to a parent component, and I need to automatically check if the data is empty or has a value. This code snippet is from my login.component.ts - child TypeScript file: @Output() update = ne ...

Return true for cucumber datatable in typescript without fail

I am facing an issue where the following step definition always returns true even for incorrect data from the dataTable. Can someone assist me in correcting the syntax in TypeScript with Chai assertions? Then(/^Verify the following details in report$/, a ...

Tips for restricting the signature within a function depending on the argument's value

Trying to consolidate interface methods into a single function with an additional operation parameter. The function can be called as expected, but struggling to narrow the signature within the function. Found some assistance in this SO post, but still enco ...

Implementing webrtc functionality in Angular 2: A beginner's guide

I attempted to integrate webrtc into my Angular 2 TypeScript project and encountered the following error: navigation.getUserMedia is not a function. Below is the code I used: ngOnInit(): void { navigator.getUserMedia(this.constraints, stream =& ...

Steps for incorporating a filter feature in an Angular Material table

.HTML: Can someone assist me with implementing a filter in this component? I tried using it with the expansion table, but unfortunately, the filter is not working as expected. <mat-dialog-content style="width: 63rem; overflow: initial;"&g ...

Incorporating an external SVG file into an Angular project and enhancing a particular SVG element within the SVG with an Angular Material Tooltip, all from a TypeScript file

Parts of the angular code that are specific |SVG File| <svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="950" height="450" viewBox="0 0 1280.000000 1119.000000" preserveAspectRatio= ...

Is it possible for a C++ array to reach the memory boundary?

Is it possible in C++ standard (and C as well) to create a pointer to one element past the end of an array without dereferencing it? Does this mean that arrays will always be allocated in such a way that their last element does not reach the memory boundar ...

Extending an interface in TypeScript does not permit the overriding of properties

While working with Typescript, I encountered an issue where I couldn't make a property not required when overwriting it. I have defined two interfaces: interface IField { label: string; model: string; placeholder? ...

Using Typescript in combination with snowpack may result in nullish coalescing operators being generated when targeting a version lower than ES2020

I've been working on compiling my TypeScript code/packages to ensure compatibility with Safari Version less than 14. After researching, I discovered that nullish coalescing operators (??) are not allowed in the targeted version. Despite changing my t ...

Guide on adding up a column from an input file passed to a CombiTimeTable in Modelica

I am currently using a .txt file (T_in1) as input in a 2D-CombiTimeTable within Modelica. This .txt file contains an array with dimensions of (4,2); the first column represents time and the second column represents the time-dependent variable. My goal is ...