5

Am new to angular and typescript and I have this function

 onSetValues(user){ //user is an object
    console.log(user);  
 }

The console.log above returns an object of the form

role:"administrator"
status:10
tries:2

I would like to transform thisto an array so that i can loop through them like

for(var i=0; i<array.length; i++){
 //do m stuff here
  }

How do i convert this

I have checked on this link but it doesnt offere help in angular2/typescript

I have also tried

console.log(user| {}) //also fails
Community
  • 1
  • 1
Geoff
  • 6,277
  • 23
  • 87
  • 197
  • 1
    Why do you want to do this? You can loop through the properties of your object directly if this would be the only reason. – malifa Jan 29 '17 at 17:08

3 Answers3

8

If you really want to convert your object values to array... you would have to do this.

  let user = {
    role:"administrator",
    status:10,
    tries:2,
  };

  let arr = [];
  for(let key in user){
   if(user.hasOwnProperty(key)){
     arr.push(user[key]);
   }
  }
  console.log(arr);

Result from console.log

0:"administrator" 1:10 2:2

penleychan
  • 5,370
  • 1
  • 17
  • 28
3

You can create an interface with the properties,

interface user{
  role: string;
  status: string;
  tries: number;
}

Create an array inside the appcomponent,

 users: user[] = [];

And then you can push the user object and make as a array,

this.users.push(user);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • sorry that should be this.users – Sajeetharan Jan 29 '17 at 08:12
  • This now creates an array but its an array of this object but i wantend the values to be pushed to an array, What i mean is this it creates an array of the form ((array(0->the user obect))) what i was looking for is an array of the form(array(role:"",status:10,...)) – Geoff Jan 29 '17 at 08:24
  • so the push pushes the object to the array but am looking for a way to push the object properties(status,role, tries) and make them an array – Geoff Jan 29 '17 at 08:25
0

Just put the response data inside a square bracket.

And save it in the class.

this.servicename.get_or_post().subscribe(data=> this.objectList = [data]);
Krishna Vyas
  • 1,009
  • 8
  • 25
vino
  • 107
  • 1
  • 4