获取值 1 对象在 Angular5



我想获取我的对象月份的所有值 ->

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

首先我的对象是假的,但后来我的用户改变了一个真,然后我需要知道那个月是真的。

我不想做 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;
}
}
}

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

用于 in 循环。

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

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

最新更新