Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript create array with loop dynamically

Am creating a mock class, for generate example data for my Angular2 TypeScript project. Am still a beginner with programming, and struggle with the informatie that is available about TypeScript. My question:

I want to create 100 items and save them in an array. The 100 items will be generated dynamically. The static way i use is very simple, but how do I can do this dynamicly? I made a begin with some iteration code, but how can I best replace the console.log code, and let the output of the iteration be as the static data. I need some examples

mock-names.ts (Static)

export var NAMES: Name[] = [
    {"id": 01, "name": "Tony"},
    {"id": 02, "name": "Jake"}
]

mock-names-dynamically.ts (Dynamically)

export var NAMES = [];

for (let i = 1; i < 100; i++) {
    console.log(i);
}

name.ts (Name Class file)

export class Name {
    id: number;
    name: string;
}
like image 230
wintersa Avatar asked Apr 11 '16 18:04

wintersa


People also ask

How do you store for loop values in array in TypeScript?

forEach((item) => { // console. log(item); item. forEach((value) => { // console. log(value); let thing: number = value; for(var i = 0; i < thing; i++) { let weekdays: string[] = [ 'M','T','W','T','F','S','S' ]; let wkday: string = (weekdays[(i%7)]); this.

How do I create an array of objects in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!

Does JavaScript have dynamic arrays?

Like all scripting languages​​, JavaScript has dynamic arrays: their size is not predetermined, nor the type of data.


3 Answers

All you have to do is use the push function of the array in Javascript.

var NAMES = [];
for (let i = 1; i < 100; i++) {
    let newName = {
       id:i.toString(),
       name:"Tony"
    };
    NAMES.push(newName);
}
like image 136
Nick Tsitlakidis Avatar answered Sep 22 '22 13:09

Nick Tsitlakidis


ES6 Way:

 const getData = () => Array.from(new Array(100), (val, index) => ({
       id:index.toString(),
       name:"Tony"
    };);
like image 31
Andrii Kovalchuk Avatar answered Sep 23 '22 13:09

Andrii Kovalchuk


Another way of dynamic initialization, if you are not sure about the size of the array-

let list:Array<{_id:string,name:string}> = Array()

Then simply push values using a loop

list.push({_id:'it001',name:'Sam'})
like image 37
Kaushal Avatar answered Sep 21 '22 13:09

Kaushal