首页 > 解决方案 > 在数组 JSON 上搜索项目

问题描述

我正在研究 vanilla js,因为我根本不允许使用 jQuery,所以我几乎是一个初学者,所以我想要一个指南,我正在尝试从我尝试过的 JSON 文件中获取电子邮件地址做一个循环,但它永远不会到达属性电子邮件并显示它。

我试过这个:

我搜索输入文本并获取值并将其存储在 textValue 中,然后尝试使用for-loop.

var textValue = document.getElementById("email").value;
  for(var i = 0; i < localStorage.getItem(jsondata.data.length); i++)
{
  if(jsondata[i].email == textValue)
    {
      console.log(jsondata[i].email) 
    }
}
 };

这是 JSON 的外观:

{
  "data": [
    {
      "email": "nicobes@gmail.com",
      "name": "Nickole Beatrice Smith",
      "address": "398 Pleasant Pine Cir. Harrington, DE 19123",     
      "age": 45,
      "notes": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, ",
      "phoneNumbers": [
        {
          "phone": "(302) 792-8434"
        },
        {
          "phone": "(302) 792-1134"
        },
        {
          "phone": "(302) 792-2234"
        },
        {
          "phone": "(302) 792-3334"
        }
      ],
      "relatives": [
        {
          "name": "Susan M Smith"
        },
        {
          "name": "Malcolm W Smith"
        },
        {}
      ]
    }

标签: javascripthtmljson

解决方案


如果您有非唯一电子邮件,请尝试使用此代码。filter 方法处理数组中的所有项,当内部回调函数(row=>row.email==textValue)返回truthy时,该行被压入返回值,其他行则不被压入。这是按电子邮件地址过滤的

var jsondata = json.data;
var textValue = document.getElementById("email").value;
var found = jsondata.filter(row=>row.email==textValue);
console.log(result); // an array of object

如果电子邮件是唯一的,请使用查找方法。find 方法回调与上一个相同,但不同的是,它在找到第一个真值时退出。另一个区别是返回值。这个返回一个对象,搜索到的对象,但不是对象数组。

var jsondata = json.data;
var textValue = document.getElementById("email").value;
var found = jsondata.find(row=>row.email==textValue);
console.log(result); // an object

推荐阅读