简体   繁体   中英

Convert an object to an array in angular2/typescript

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

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

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

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

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