在数组JSON上搜索项目

时间:2019-06-30 19:42:15

标签: javascript html 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"
        },
        {}
      ]
    }

3 个答案:

答案 0 :(得分:2)

如果您的电子邮件不唯一,请尝试使用此代码。过滤器方法处理数组中的所有项目,并且当内部回调函数(row=>row.email==textValue)返回true时,此行将推入返回值,而其他行则不返回。这是通过电子邮件地址过滤的

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

答案 1 :(得分:1)

在您的for循环语句中,您应该搜索jsondata.data [i]而不是jsondata [i]

答案 2 :(得分:0)

您没有显示如何存储或从本地存储中检索数据。设置起来就像(假设数据存储在名为 obj 的对象中):

localStorage.setItem('data', JSON.stringify(obj));

然后获取它(检索数据,使用JSON.parse返回到名为 localData 的对象):

var localData = JSON.parse(localStorage.getItem('data'));

现在您可以搜索 localData

for(var i=0, iLen=localData.data.length; i<iLen; i++) {

  if(localData.data[i].email == textValue) {
    console.log(localData.data[i].email)
  }
}