首页 > 解决方案 > 查找输入值并将其与 JSON 数据进行比较

问题描述

我正在尝试将用户输入值与 JSON 数据进行比较。

我发现了一些与此类似的问题,但它并没有解决我的问题。

这是我的代码,你知道为什么它不起作用吗?

Javascript

fetch('js/countries.json') 
.then(res => res.json())   
.then(data => { 

  function checkCountry() {
    let input = document.getElementById("countryInput").value;
    let country = data.find(check => check.country === "Norway");
    let text;

    if (input === data[country]) {
      text = "Yes";

    } else {
      text = "No";
    }
    document.getElementById("alert").innerHTML = text;
  }

  document.getElementById("check").addEventListener("click", checkCountry);

  console.log(data);
})

JSON

[{"country":"USA","active":true},
{"country":"Spain","active":true},
{"country":"Norway","active":true}]

HTML

<form action="">
 <div class="input-container">
  <input id="countryInput" type="text" placeholder="Country">
  <i class="fas fa-search"></i>
 </div>  
  <button id="check" type="button">CHECK</button>
</form>

标签: javascriptarraysjson

解决方案


这条线不好:if (input === data[country]) {

您必须使用与上述国家/地区相同的机制进行检查...

let inputCountry = data.find(check => check.country === input);

像这样:

const data = [{"country":"USA","active":true},
{"country":"Spain","active":true},
{"country":"Norway","active":true}];


document.getElementById("check").addEventListener("click", checkCountry);
  
  
function checkCountry() {
    let input = document.getElementById("countryInput").value;
    let country = data.find(check => check.country === "Norway");
    let inputCountry = data.find(check => check.country === input);
    let text;

    // You have to check with the country
    if (inputCountry && input === inputCountry.country) {
      text = "Yes";

    } else {
      text = "No";
    }
    console.log(text);
}
<form action="">
 <div class="input-container">
  <input id="countryInput" type="text" placeholder="Country">
  <i class="fas fa-search"></i>
 </div>  
  <button id="check" type="button">CHECK</button>
</form>


推荐阅读