Javascript 如何循环2个数组以创建新的键/值对象

Javascript 如何循环2个数组以创建新的键/值对象,javascript,arrays,loops,object,Javascript,Arrays,Loops,Object,我有两个数组-CountryName和countryCodes。这些数组中的项的索引序列对齐,因为它们来自同一API,即countryNames[0]是阿富汗,countryCodes[0]是AF等 我正试图创建一个新的、独立的对象,以像JSON对象一样整齐地将数据存储在键/值对中,但我还没有成功。有人建议循环使用它们,但我不太确定该怎么做。任何帮助都将不胜感激 下面是我唯一成功使用的代码。它给了我一个对象,虽然看起来很奇怪,但它没有将数据存储在键/值对关系中 var keys = [];

我有两个数组-CountryName和countryCodes。这些数组中的项的索引序列对齐,因为它们来自同一API,即countryNames[0]是阿富汗,countryCodes[0]是AF等

我正试图创建一个新的、独立的对象,以像JSON对象一样整齐地将数据存储在键/值对中,但我还没有成功。有人建议循环使用它们,但我不太确定该怎么做。任何帮助都将不胜感激

下面是我唯一成功使用的代码。它给了我一个对象,虽然看起来很奇怪,但它没有将数据存储在键/值对关系中

 var keys = [];
 var values = [];


 fetch("https://restcountries.eu/rest/v2/all")
.then((response) => {
    return response.json();
})
.then((data) => {
    const codes = data.map(item => item.alpha2Code);
    values.push(codes);

    const names = data.map(item => item.name);
    keys.push(names);

    var result = [];
    keys.forEach((key, i) => result[key] = values[i]);
    console.log(result);
});
我只想吃点像这样的东西- { CountryName:CountryCode, 2ndCountryName:2ndCountryCode, 第三国家名称:第三国家代码, 等 };

Fetchhttps://restcountries.eu/rest/v2/all.thenresponse => { return response.json; }.thendata=>{ var result={} 对于变量i=0;i}; 阵列。减少救援:

Fetchhttps://restcountries.eu/rest/v2/all .thenresponse=>{ return response.json; } .thendata=>{ const result=data.reducecountries,项=>{ 国家[项目名称]=项目字母代码; 返回国; }, {}; console.logresult; }; var键=[]; var值=[]; Fetchhttps://restcountries.eu/rest/v2/all .thenresponse=>{ return response.json; } .thendata=>{ 常量代码=data.mapitem=>item.alpha2Code; 值。代码; const names=data.mapitem=>item.name; 键。键名; var结果=[]; 键[0]。forEachkey,i=>{ 常量obj={}; obj[values[0][i]]=键; 结果:pushobj; } ; console.logresult;
};我知道有人问过类似的问题,我已经尝试过那里提出的每一个解决方案——没有什么对我有效,我不确定为什么。我已经设法使它与下面的代码,我标记为最有帮助的工作。谢谢大家!请不要只发布代码作为答案,而是解释代码的作用以及如何解决问题。带有解释的答案通常质量更高,更有可能吸引更多的选票。
fetch("https://restcountries.eu/rest/v2/all")
.then((response) => {
    return response.json();
})
.then((data) => {
  const results = data.reduce((agg, item) => {
    agg[item.name] = item.alpha2Code
    return agg
  }, {})
  console.log(results)
})