为货币数据数组重新分配键名,构建货币转换专用新数组
转换JSON货币数据为新结构数组
没问题,我帮你搞定这个货币数据结构转换的事儿~首先先明确下你给的原始JSON数据结构(补全了截断部分):
{ "eur": { "code": "EUR", "alphaCode": "EUR", "numericCode": "978", "name": "Euro", "rate": 0.83563518721183, "date": "Mon, 7 May 2018 00:00:01 GMT" }, "gbp": { "code": "GBP", "alphaCode": "GBP", "numericCode": "826", "name": "U.K. Pound Sterling", "rate": 0.73757713865121, "date": "Mon, 7 May 2018 00:00:01 GMT" } }
假设你需要将其转换为数组格式,并且重新分配键名(比如把rate改成exchangeRate、name改成currencyName这类更贴合货币转换场景的命名),可以用JavaScript来实现,代码如下:
// 原始货币JSON数据 const originalCurrencyData = { "eur": { "code": "EUR", "alphaCode": "EUR", "numericCode": "978", "name": "Euro", "rate": 0.83563518721183, "date": "Mon, 7 May 2018 00:00:01 GMT" }, "gbp": { "code": "GBP", "alphaCode": "GBP", "numericCode": "826", "name": "U.K. Pound Sterling", "rate": 0.73757713865121, "date": "Mon, 7 May 2018 00:00:01 GMT" } }; // 转换为自定义结构的数组 const convertedCurrencyArray = Object.entries(originalCurrencyData).map(([_, currency]) => ({ currencyCode: currency.code, currencyName: currency.name, exchangeRate: currency.rate, lastUpdated: currency.date, // 如果你需要保留其他原始字段,比如numericCode,直接添加即可 numericCode: currency.numericCode })); // 输出转换后的结果 console.log(convertedCurrencyArray);
转换后的数组结构如下(完全符合货币转换操作的使用场景):
[ { "currencyCode": "EUR", "currencyName": "Euro", "exchangeRate": 0.83563518721183, "lastUpdated": "Mon, 7 May 2018 00:00:01 GMT", "numericCode": "978" }, { "currencyCode": "GBP", "currencyName": "U.K. Pound Sterling", "exchangeRate": 0.73757713865121, "lastUpdated": "Mon, 7 May 2018 00:00:01 GMT", "numericCode": "826" } ]
关键步骤说明
Object.entries():把原始的对象型数据拆分成键值对数组,方便后续遍历处理.map():遍历每个货币条目,按照你需要的键名重新构造对象,你可以根据实际需求修改键名或者增减字段(比如不需要numericCode就删掉对应行,或者添加alphaCode)
内容的提问来源于stack exchange,提问作者pazta
相关产品推荐
相关产品推荐

