EduBw
EduBw

Reputation: 942

get value the 1 Object in Angular5

I want get all values the my Object Month ->

 public months: Months = {
        jan: false, 
        feb: false, 
       etc...
    }

First my object is false but then my user changed a true, then I need know that month is true.

I don't want do 12 if ...

  if (months.jan) { ... }

I am trying with

   let responseProps = Object.keys(this.months);

   console.log('responseProps ', responseProps ); //I get 0º->jan, 1->feb..
   // but I don't get "true or false"
   for (prop of responseProps) {
       console.log('prop', prop );
    }

or with ->

 for (prop of this.months) { //Now I get error because this.month isn't array.
       console.log('prop', prop );
    }

thanks.

Edit ->

public months: Months = {
            jan: false, -> index 0
            feb: false, -> index 1
           etc...
        }

 searchMonth(year: string, selectMonth: number) {

    if (selectMonth === undefined) {
        let obKeys = Object.keys(this.months), prop: string, month: number;
        /*Get first Month*/
        for (prop of obKeys) {
            if (this.months[prop]) {
                month = prop; // HERE I NEED the number of month
                break;
            }
        }

    }

Upvotes: 0

Views: 35

Answers (3)

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

Use the in operator to loop over Objects instead of of.

var months = {
        jan: false,
        feb: true,
    }
    
    for (var eachMonth in months) {
      // in operator will also return true for props in prototype chain, hence the below check
      if (months.hasOwnProperty(eachMonth)) {   
        console.log(eachMonth, months[eachMonth]);
      }
    }

// If you want to use Object.keys()
var obKeys = Object.keys(months); // this will not give props from prototype, so no further check
for (prop of obKeys) {
   console.log('prop: ', prop, ", month index: ", obKeys.indexOf(prop), "value: ", months[prop] );
}

Upvotes: 2

Krishna Rathore
Krishna Rathore

Reputation: 9687

use this.months[prop]

let responseProps = Object.keys(this.months);
console.log('responseProps ', responseProps);
// but I don't get "true or false"
for (prop in this.months) {
    console.log('prop', this.months[prop]);
}

Upvotes: 0

Ankit Sharma
Ankit Sharma

Reputation: 1704

Use for in loop.

for (key in this.months) {
   console.log('prop', this.months[key] );
}

Upvotes: 0

Related Questions