Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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;
}
share|improve this question
1  
Where the names values will come from? Also, it seems that you have a class called Name, could post this class here? – vintem Apr 11 '16 at 18:28
    
The class name.ts is used. I added the class to my post. – wintersa Apr 11 '16 at 18:38
up vote 3 down vote accepted

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);
}
share|improve this answer
    
Thank you, I understand what your code is doing. I will try this! – wintersa Apr 11 '16 at 18:40
    
I works but not completely for me. The 100 items are created with only the name, and without the Id. I need to figure that out. But am now at the right direction, thanks. – wintersa Apr 11 '16 at 18:46
    
Based on my code snippet, the id of each object should be a string representation of the i value. Please double check your code. – Nick Tsitlakidis Apr 11 '16 at 18:49
    
This was stupid The problem was in my class, sorry. But again thanks! – wintersa Apr 11 '16 at 19:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.