【发布时间】:2021-12-31 20:41:30
【问题描述】:
您好,我在根据用户选择获取特定信息时遇到了一些问题。 我想获取 newsAPI ,数组里面有包含国家的对象。 用户使用下拉菜单选择他想要的国家,但是当我使用 map() 时有一个迭代国家它传递所有具有重复项的国家,我试图删除重复项,但它不起作用 + 我使用了 reduce() 但它也不起作用。 有没有什么提示和建议,也许我错过了什么。
html:
<html>
<div class="ui container" id="seachCountry"></div>
</html>
脚本:
<script>
const apikey = 'https://newsapi.org/v2/top-headlines/sources?category=sports&apiKey=b23fd6aac9c44682abb9580dae85d23f';
async function getNews(){
const response = await fetch(apikey);
const data = await response.json();
printCards(data)
}
function printCards(data) {
const header = document.querySelector('#seachCountry');
//Inside "header.innerHTMI", I put map() function to pass all items but I couldn't prevent duplicates
header.innerHTML += `
<select class='ui fluid selection dropdown select' onchange="getCountry(this.value)">
<option>select the country</option>
${data.sources.map( countryName => `<option>${countryName.country}</option>`)}
</select>`
// print all country name using map and dispaly it to user in dropdown WIHT deplicate country name
}
async function getCountry(e){
if ( e !== 'select the country'){
//Another Fetch based on user choice
const response = await fetch(`${apikey}&country=${e}`)
const data = await response.json();
console.log(data.sources)
//It only shows the information of the country in which the user is interested
document.getElementById("output").innerHTML = data.sources.map(countryName =>
`<div class="ui container card">
<div class="content">
<h4 class="header">${countryName.name}</h4>
</div>
<div class="content">
<div class="desc">${countryName.description}</div>
</div>
<div class="extra content">
<span>
<a href=${countryName.url} target="_blank" class="ui button btn">Read more</a>
</span>
</div>
</div>`)
}
}
getNews()
</script>
【问题讨论】:
标签: javascript json api object dropdown