嗨,我在根據用戶選擇獲取特定資訊時遇到了一些問題。我想獲取 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 >
<div >
<h4 >${countryName.name}</h4>
</div>
<div >
<div >${countryName.description}</div>
</div>
<div >
<span>
<a href=${countryName.url} target="_blank" >Read more</a>
</span>
</div>
</div>`)
}
}
getNews()
</script>
看這張圖澄清問題
uj5u.com熱心網友回復:
您可以使用此函式將陣列過濾為僅具有不同的值:
source.filter((item, index) => source.indexOf(item) === index);
因此,在您的情況下,您要映射到options串列,它將是這樣的:
function printCards(data) {
const header = document.querySelector('#seachCountry');
const countries = data.sources.map(cn => cn.country);
const distinctCountries = countries.filter((country, index) => countries.indexOf(country) === index);
header.innerHTML = `
<select class='ui fluid selection dropdown select' onchange="getCountry(this.value)">
<option>select the country</option>
${distinctCountries.map(country => `<option>${country}</option>`)}
</select>`;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/363333.html
標籤:javascript json 接口 目的 落下
