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
1
  • 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. Commented Jan 29, 2017 at 17:08

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

sorry that should be this.users
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,...))
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
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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.