如何根据搜索值从JavaScript数组中获取值?

时间:2015-09-14 20:38:59

标签: javascript json

当涉及到JavaScript时,我是一个菜鸟,但我一直在试图解决这个问题。任何帮助将不胜感激。样本和教程网​​站也会有所帮助。我的问题是如何将此搜索功能合并到一个带有邮政编码的JSON文件中,并返回带有该zip的数组以及随之而来的其他数据。对不起,如果这似乎没有任何研究,请相信我,我一直在玩这个太长时间,我只需要一些方向让我开始。提前谢谢。

所以我有这样的表格:

<form>
      <input type="text" name="zip" id="zip" placeholder="Zip Code">
      <button onclick="getZip(event);">Check</button>
</form>

JavaScript的:

<script>
function getZip(e){
e.preventDefault();
var zip = document.getElementById('zip').value; // Gets the value from the text field "zip" on the form.
  if (zip === "") { // Checks if the text field "zip" is empty, if so it returns an error message.
      alert ('Please enter a zip code!');
  }
    else if (zip.length > 5) {
      alert ("Please enter a valid 5 digit numeric zip code.");
    }

    else if (isNaN(zip))  { // Checks if the text field "zip" for alphabetic characters. The "isNaN" function is to determine if a value does not convert to a number, if so it returns an error message. 
        alert("Please enter a numeric value.");

    } else if (zip.length == 5) {
      alert("Success! " + zip);

    } else { // Returns value from the text field "zip" on the form.
      alert(zip);
  }

  return false;
}

</script>

JSON示例:

[ {
    "ZipCode": 48650,
    "City": "Pinconning",
    "State": "Michigan",
    "StateAbbreviation": "MI",
    "County": "Bay"
},
{
    "ZipCode": 48651,
    "City": "Prudenville",
    "State": "Michigan",
    "StateAbbreviation": "MI",
    "County": "Roscommon"
    }
]

1 个答案:

答案 0 :(得分:0)

你最好的选择是使用loadash。如果JSON在服务器端,那么您可以使用服务器端语言来解析json并过滤结果。

如果服务器端代码是nodejs

,则可以使用lodash完成

如果客户端然后使用JSON.parse将json转换为javascript对象并使用loadash的 map 方法根据需要提取数据。