获得值Angular5中的1个对象

时间:2018-08-23 10:04:37

标签: angular

我想在“对象月份”中获取所有值->

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

首先,我的对象为false,但随后用户更改为true,那么我需要知道月份为true。

如果...我不想做12

  if (months.jan) { ... }

我正在尝试

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

或带有->

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

谢谢。

编辑->

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

    }

3 个答案:

答案 0 :(得分:2)

使用in运算符而不是Objects遍历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] );
}

答案 1 :(得分:0)

用于循环。

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

答案 2 :(得分:0)

使用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]);
}