Home how to use property of object in loop?
Reply: 4

how to use property of object in loop?

Amir Gh
Amir Gh Published in 2018-01-11 16:06:39Z

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

Sajeetharan Reply to 2018-01-11 17:58:32Z


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

for(let result of this.address){


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]);
Lazar Ljubenović
Lazar Ljubenović Reply to 2018-01-11 16:09:06Z

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:

  <li *ngFor="let key of keys">{{ key }} {{ object[key] }}</li>
Sachila Ranawaka
Sachila Ranawaka Reply to 2018-01-11 16:09:42Z

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
Santosh Reply to 2018-01-11 17:20:08Z

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.');
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.313041 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO