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
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.
To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .
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 .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With