Amir Gh
Amir Gh

Reputation: 285

how to use property of object in loop?

I want to have a loop with some properties of a class, not all of it's properties. I want to implement a function for properties of the class. But even I don't know how to set the length of loop with number of properties in class. For example this is my class:

class Address{
id: number,
street: string,
state: string,
}

and I want to make a loop with length of the object of this class and do something on each property of this object of Address class, something like this:

for (let i; i< /*length of address object*/; i++) {
if (/*each property of address */) {
// do sth
 }
}

I'm using Angular 4. Thank you

Upvotes: 0

Views: 173

Answers (4)

Sajeetharan
Sajeetharan

Reputation: 222582

LOOP OVER ARRAY OF OBJECTS:

I assume you are refering to array of objects, with that you can do

for(let result of this.address){
    console.log(result.street);
    ....
    etc
}

LOOP OVER OBJECT KEYS :

in case if its an object, you can get the keys using Object.keys and then loop over them.

objectKeys = Object.keys(this.address);

for (let result of this.objectKeys) {
    console.log('key', result);
    console.log('value', this.address[result]);
} 

Upvotes: 1

Santosh
Santosh

Reputation: 11

I assume that you want to access property of each Address Object. assuming that : addresses: Address[];

You need to use underscore.js library first and import it in your class.

import * as _ from 'underscore'

Now you can use '_' function in your code as follow:

do(addresses=> {
    _.each(addresses, (address: Address) => {
          if (address.state === "CA") {
            console.log('This is California.');
          }
     });
  });

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41427

Create a new instance of address class and get the object properties using Object.keys

address: Address = new Address()

keyArr = Object.keys(this.address)

for (let i; i< this.keyArr ; i++) {
if (/*each property of address */) {
// do sth
 }
} 

Upvotes: 1

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

Since you've tagged this as an Angular question, I'll assume you want to print this in Angular template. Otherwise it's not Angular at all.

You cannot loop over objects because there is no specified order in which the loop should happen. You must convert your object into an array. One way to do this is to use Object.keys method.

this.keys = Object.keys(object)

Then loop over this in your template:

<ul>
  <li *ngFor="let key of keys">{{ key }} {{ object[key] }}</li>
</ul>

Upvotes: 0

Related Questions