Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 784
Geoff Avatar asked Jan 29 '17 07:01

Geoff


People also ask

How do you push an object to an array in angular2 and TypeScript?

To push an object to an array: Set the type of the array to Type[] . Set the type of the object to Type . Use the push() method to push the object to the array.

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .

How do I cast an array in TypeScript?

To cast arrays with TypeScript, we can use the as keyword or add the variable name before the array expression. const a = x as Array<number>; to cast x to a number array with as .


2 Answers

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

like image 165
penleychan Avatar answered Oct 10 '22 15:10

penleychan


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);
like image 21
Sajeetharan Avatar answered Oct 10 '22 13:10

Sajeetharan