简体   繁体   中英

Get an array of property values from an object array in typescript

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

    array1?: string[];
}

Imagine that the array is initialized with a bunch of data from an API response. I have an array of Test objects. What I now need is to extract the Name of all those objects in that array into a new array. I could not find typescript syntax for this problem.

What I now need is to extract the Name of all those objects in that array into a new array

Use Array.prototype.map : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Fix

From Name[] you want string[] :

const array1: string[] = names.map(x=>x.fieldThatIsTheStringYouWant);

Typescript is (more or less) a superset of javascript. The same solution for Javascript would apply to Typescript.

const output = input.map( item => item.name );
  var originalObject = [
        {"first":"Gretchen","last":"Kuphal","email":"greenwolf54@gmail.com","address":"416 
                            Lesch Road","created":"March 1, 2012","balance":"$9,782.26"}];

1.you want to copy array simply

var duplicateObject = originalObject;

  1. If you want all you can loop
  2. If you want access one value simply do this

duplicateObject[0].first

alert(duplicateObject[0].first);

Editrd This can be done also

var originalObject = [
  {"first":"Gretchen","last":"Kuphal","email":"greenwolf54@gmail.com","address":"416 Lesch Road","created":"March 1, 2012","balance":"$9,782.26"},
{"first":"Morton","last":"Mayer","email":"salmonsquirrel25@gmail.com","address":"1602 Bernhard Parkway","created":"April 29, 2017","balance":"$6,596.11"},
{"first":"Catalina","last":"Daugherty","email":"Catalina.Daugherty@filomena.name","address":"11893 Kali Vista","created":"October 16, 2008","balance":"$6,372.86"},
{"first":"Orpha","last":"Heaney","email":"turquoisewolf22@gmail.com","address":"8090 Chris Stream","created":"November 21, 2015","balance":"$9,596.26"},
{"first":"Reva","last":"Mohr","email":"Reva.Mohr@oda.net","address":"0291 Kailyn Stravenue","created":"November 6, 2014","balance":"$4,768.37"},
{"first":"Loma","last":"Keeling","email":"turquoisegiraffe09@gmail.com","address":"84460 Samson Knoll","created":"June 13, 2017","balance":"$9,361.16"}
];

var duplicateObject=new Array(); 

for (let num of originalObject) {
    duplicateObject.push(num.first);
}
// print
for (let first of duplicateObject) {
    console.log(first);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM