如何遍历2个数组以创建新的键/值对象

时间:2019-09-27 14:47:08

标签: javascript arrays loops object

我有2个数组-countryNames和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,
3rdCounryName:3rdCountryCode,
等.....
};

4 个答案:

答案 0 :(得分:1)

Array.reduce进行救援:

fetch("https://restcountries.eu/rest/v2/all")
  .then((response) => {
    return response.json();
  })
  .then((data) => {
      const result = data.reduce((countries, item)=> {
      	countries[item.name] = item.alpha2Code;
        return countries;
      }, {});
      console.log(result);
  });

如果您想了解更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

答案 1 :(得分:0)

fetch("https://restcountries.eu/rest/v2/all").then((response) => {
	return response.json();
}).then((data) => {
	var result = {}
	for (var i = 0; i < data.length; i++) {
		result[data[i].name] = data[i].alpha2Code;
	}
	console.log(result);
});

答案 2 :(得分:0)

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)
})

答案 3 :(得分:0)

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[0].forEach((key, i) => {
       const obj = {};
       obj[values[0][i]] = key;       
       result.push(obj);
     }
    );
    
    console.log(result);
});