3
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.

1

3 Answers 3

4

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 );
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

0
  var originalObject = [
        {"first":"Gretchen","last":"Kuphal","email":"[email protected]","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":"[email protected]","address":"416 Lesch Road","created":"March 1, 2012","balance":"$9,782.26"},
{"first":"Morton","last":"Mayer","email":"[email protected]","address":"1602 Bernhard Parkway","created":"April 29, 2017","balance":"$6,596.11"},
{"first":"Catalina","last":"Daugherty","email":"[email protected]","address":"11893 Kali Vista","created":"October 16, 2008","balance":"$6,372.86"},
{"first":"Orpha","last":"Heaney","email":"[email protected]","address":"8090 Chris Stream","created":"November 21, 2015","balance":"$9,596.26"},
{"first":"Reva","last":"Mohr","email":"[email protected]","address":"0291 Kailyn Stravenue","created":"November 6, 2014","balance":"$4,768.37"},
{"first":"Loma","last":"Keeling","email":"[email protected]","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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.