You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将包含货币信息的Object列表转换为指定键值对Object?

数组转键值对对象的实现方案

这是个很常见的数据结构转换需求,我给你分享几种JavaScript下的实现方式,都是针对你给出的JSON数组场景:

1. 现代JS首选:Array.reduce()

这是最简洁且常用的写法,利用数组的reduce方法逐步构建目标对象:

const currencyArray = [ {"id":1,"name":"USD - US Dollar","country":"US","created_at":"2018-05-28 14:54:24","updated_at":"2018-05-28 14:54:24"}, {"id":2,"name":"TH- Thai Bat","country":"TH","created_at":"2018-05-28 14:54:24","updated_at":"2018-05-28 14:54:24"} ];

const mappedCurrency = currencyArray.reduce((acc, currentItem) => {
  acc[currentItem.country] = currentItem.name;
  return acc;
}, {});

console.log(mappedCurrency);
// 输出:{"US": "USD - US Dollar","TH": "TH- Thai Bat"}

逻辑说明:reduce的第一个参数是回调函数,acc是我们要构建的空对象(第二个参数{}是初始值),每次遍历数组元素时,把当前元素的country作为键、name作为值存入acc,最后返回这个累加后的对象。

2. 兼容性友好:传统for循环

如果需要兼容较老的浏览器环境,传统循环写法更稳妥:

const currencyArray = [ {"id":1,"name":"USD - US Dollar","country":"US","created_at":"2018-05-28 14:54:24","updated_at":"2018-05-28 14:54:24"}, {"id":2,"name":"TH- Thai Bat","country":"TH","created_at":"2018-05-28 14:54:24","updated_at":"2018-05-28 14:54:24"} ];

const mappedCurrency = {};
for (let i = 0; i < currencyArray.length; i++) {
  const item = currencyArray[i];
  mappedCurrency[item.country] = item.name;
}

console.log(mappedCurrency);
// 同样得到目标结果

逻辑说明:先初始化空对象,然后遍历数组的每一项,直接给对象赋值对应的键值对,逻辑直观,没有API兼容性问题。

3. ES2019+简洁写法:Object.fromEntries()

如果你的运行环境支持ES2019及以上,这种写法会更优雅:

const currencyArray = [ {"id":1,"name":"USD - US Dollar","country":"US","created_at":"2018-05-28 14:54:24","updated_at":"2018-05-28 14:54:24"}, {"id":2,"name":"TH- Thai Bat","country":"TH","created_at":"2018-05-28 14:54:24","updated_at":"2018-05-28 14:54:24"} ];

const mappedCurrency = Object.fromEntries(
  currencyArray.map(item => [item.country, item.name])
);

console.log(mappedCurrency);

逻辑说明:先用map把原数组转换成[键, 值]格式的二维数组,再通过Object.fromEntries直接将二维数组转换为目标对象,代码非常简洁。

注意事项

如果原数组中存在多个相同country的元素,后面元素的name会覆盖前面的,这个是所有方案的共同特性,需要根据你的业务场景提前处理重复数据。

内容的提问来源于stack exchange,提问作者tree em

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:47:20