Hello Guys我有一个问题,因为我有一个任务来获取API然后按特定顺序显示结果:
但我得到的是:
let toObject = (array) =>
array.reduce((obj,item) => {
obj[item.name.toUpperCase()] = item
return obj
}, {})
fetch('https://restcountries.eu/rest/v2/')
.then((resp) => resp.json())
.then((data) => data.filter(x => x.borders.includes('POL')))
.then(data => toObject(data))
.then(data => Object.entries(data).map(([key, value]) => ({ [key]: value }))).then(data => console.log(data))
但它看起来并不像是什么样子。我不知道要添加什么,所以我的代码返回结果,如截图中的结果:(
答案 0 :(得分:0)
这是您实现同样目标的一种方式。它主要使用Array#reduce
将结果转换为所需的对象。
// Get the data using AJAX
$.get('https://restcountries.eu/rest/v2/')
.then(data => {
// Transform the results
let transformed = data.reduce((acc, item) => {
// In each iteration, assign the country's name as key to the accumulator
acc[item.name.toUpperCase()] = {
// Calculate neighbours using borders count
hasMoreThanFourNeighbours: item.borders.length > 4 ? "YES" : "NO",
// Area with suffix KM2
area: item.area + " KM2",
// Population
population: item.population
};
// Return the accumulator for next iteration
return acc;
}, {});
console.log(transformed);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:0)
尝试使用地图
fetch('https://restcountries.eu/rest/v2/')
.then((resp) => resp.json())
.then((data) => data.filter(x => x.borders.includes('POL')))
.then((data) => data.reduce((obj, item) => {
obj[item.name.toUpperCase()] = {
hasMoreThanFourNeighbors: item.borders.length > 4 ? 'YES' : 'NO',
population: item.population,
area: item.area + ' KM2'
};
return obj;
}, {}))
.then(data => console.log(data))