如何使用对象的键填充选择框值?

时间:2017-06-11 06:31:00

标签: angular

我有一个像这里的对象,

{
  "USD": {
    "symbol": "$",
    "name": "US Dollar",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "USD",
    "name_plural": "US dollars"
  },
  "CAD": {
    "symbol": "CA$",
    "name": "Canadian Dollar",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "CAD",
    "name_plural": "Canadian dollars"
  },
}

我想用键(USD,CAD)填充选择框。

我目前的实施,

public currencyList;
getCurrency() {
        let currencyCode = this.currencyDetails.getCurrencyDetails();
        for (var key in currencyCode) {
            if (currencyCode.hasOwnProperty(key)) {
                this.currencyList.push(key);
            }
        }
    } 

3 个答案:

答案 0 :(得分:0)

您需要遍历属性并使用Object.keys将其添加到如下所示的数组变量中。

var obj = {
"USD": {
"symbol": "$",
"name": "US Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "USD",
"name_plural": "US dollars"
},
"CAD": {
"symbol": "CA$",
"name": "Canadian Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "CAD",
"name_plural": "Canadian dollars"
},
}

public currencyList;
getCurrency() {
    let currencyCode = this.currencyDetails.getCurrencyDetails();
    currencyList = Object.keys(currencyCode);
} 

现在将绑定到您的选择框元素,它可以正常工作

答案 1 :(得分:0)

Jaykrishnan的答案很好,你也可以通过这样做来缩短它:

getCurrency() {
   this.currencyList = Object.keys(this.currencyDetails.getCurrencyDetails());
} 

然后你可以在模板中使用currencyList :)

<select>
  <option *ngFor="let key of currencyList">  
     {{key}}
  </option>
</select>

答案 2 :(得分:0)

首先,您的JSON无效,最后不应包含 , 。您只需使用 Object.keys(this.currencyList);

即可
export class AppComponent {
 currencyKeys;
 currencyList = {
"USD": {
"symbol": "$",
"name": "US Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "USD",
"name_plural": "US dollars"
},
"CAD": {
"symbol": "CA$",
"name": "Canadian Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "CAD",
"name_plural": "Canadian dollars"
}
};
currencyKeys = Object.keys(this.currencyList);

)
}

<强> DEMO