javascript - 向对象中的选择添加选项? (JS)

标签 javascript ecmascript-6

尝试构建货币转换器应用程序,但我在向选择元素添加选项时遇到问题。我想在选项中包含名称(美元)和值(value)(1.23)。 我尝试将对象转换为数组以使用 map ,但似乎不起作用。

任何帮助将不胜感激。

HTML

<div id="msg"></div>
<input type="number" autofocus id="input">
<select id="rateFrom">
</select>
 <hr>
<input type="number" disabled id="output">
<select id="rateTo">
</select>

JS

const select = document.getElementById('rateFrom'); 
const url = 'https://api.fixer.io/latest?base=USD'; // get currency rates
fetch(url)
.then(response => {
    if (response.status !=200) {
        document.getElementById('msg').innerHTML=`<p>SYSTEM IS OFFLINE 
(${response.status})</p>`
    }else{
        return response.json();
    }
})
.then(data => {
    console.log(data);
 document.getElementById('msg').innerHTML=`<p>SYSTEM IS ONLINE (LAST UPDATE 
 WAS @ ${data.date})</p>`
 let rates = data.rates;
 console.log(rates);
 rates = Object.keys(rates).map(function (key) {  //convert object to array
 return { [key]: rates[rates] };
 })
 console.log(rates);
 return rates.map(function(rate) { // map through the rates and for each run 
 the code below


let el = document.createElement("option");
 el.textContent = rate;
 el.value = rate;
 select.appendChild(el);
 })
 })

最佳答案

您的中有一些错误。然后尝试下面的选项,它会在选项中显示名称+值

const select = document.getElementById('rateFrom'); 
const url = 'https://api.fixer.io/latest?base=USD'; // get currency rates

fetch(url)
.then(response => {
    if (response.status !=200) {
        document.getElementById('msg').innerHTML=`<p>SYSTEM IS OFFLINE (${response.status})</p>`
    }else{
        return response.json();
    }
})
.then(data => {
      document.getElementById('msg').innerHTML=`<p>SYSTEM IS ONLINE (LAST UPDATE WAS @ ${data.date})</p>`

      let rates = data.rates;

      // data from url doesn't have USD 1.23 like you mentioned in your question, 
      // but if you want to add it manually do this:
      let usdOption = document.createElement("option");
      usdOption.value = 'USD';
      usdOption.textContent = 'USD '+1.23;
      select.add(usdOption)

      // populating options with data from the url
      Object.keys(rates).map(function (key) {
	  let el = document.createElement("option");
    	  el.value = key;
	  el.textContent = key + ' ' + rates[key];
 	  select.add(el)
     })
 })
<div id="msg"></div>
<input type="number" autofocus id="input">
<select id="rateFrom">
</select>
 <hr>
<input type="number" disabled id="output">
<select id="rateTo">
</select>

关于javascript - 向对象中的选择添加选项? (JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46755172/

相关文章:

javascript - 是否可以对 ES6 map 对象进行排序?

abstract-syntax-tree - 如何将ES6 AST直接转换为ES5 AST?

javascript - 在javascript中获取另一个元素内的html元素

java - 在 Haxe 中检测目标语言

javascript - Promise 模式 - 使用 Promise.all()

javascript - 如何修复重复导入?

javascript - 在 redux-saga 中等待

javascript - 'as' 语句 Angular 2 +/javascript

javascript - 无法使用 Express 和 Mongoose 存储新用户

Javascript -> Flash 抛出 "Error calling method on NPObject"