[英]How to iterate over objects stored in a JavaScript array
I'm coding a simple JavaScript currency converter.我正在编写一个简单的 JavaScript 货币转换器。 Pulled the currency data from an API and stored it to a state object.
从 API 中提取货币数据并将其存储到 state object。 Next, I wanted to add currency name, country and symbol to the app so I'm pulling that data from a Rest Countries API and storing it to "currencies" array.
接下来,我想将货币名称、国家和符号添加到应用程序中,因此我从 Rest 国家 API 中提取该数据并将其存储到“货币”数组中。
Here's the code:这是代码:
export const state = {
date: [],
time: {},
currency: [],
rates: {},
result: [],
};
export const getSymbolsCountry = async function (symbol) {
try {
const data = await fetch(`https://restcountries.eu/rest/v2/currency/${symbol}`);
const json = await data.json();
addInfoToSymbol(json[0]);
} catch (err) {
console.log(err);
}
};
function addInfoToSymbol(data) {
let country = {
code: data.currencies[0].code,
symbol: data.currencies[0].symbol,
flag: data.flag,
country: data.name,
};
state.currency.push(country);
}
Console logging the currency from state shows that it's an array but using map or forEach on it does nothing.从 state 记录货币的控制台显示它是一个数组,但在其上使用 map 或 forEach 什么也不做。 console log state.currency Could someone please help me understand what I'm doing wrong cause I can't wrap my head around it.
控制台日志 state.currency有人可以帮我理解我做错了什么,因为我无法理解它。
What do you mean by using map of forEach on it does nothing ?使用 forEach 的 map什么都不做是什么意思?
Here is an example where I use forEach
on state.currency
and its working perfectly.这是我在
state.currency
上使用forEach
的示例,它运行良好。
const state = { currency: [] }; const getSymbolsCountry = async function (symbol) { try { const data = await fetch(`https://restcountries.eu/rest/v2/currency/${symbol}`); const json = await data.json(); addInfoToSymbol(json[0]); } catch (err) { console.log(err); } }; function addInfoToSymbol(data) { let country = { code: data.currencies[0].code, symbol: data.currencies[0].symbol, flag: data.flag, country: data.name, }; state.currency.push(country); } Promise.all([ getSymbolsCountry("EUR"), getSymbolsCountry("USD"), getSymbolsCountry("JPY") ]).then(() => state.currency.forEach(({code}) => $("#result").append("<li>" + code + "</li>") ) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="result"></ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.