javascript - 在数组 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"
},
{}
]
}
解决方案
如果您有非唯一电子邮件,请尝试使用此代码。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
推荐阅读
- android - 空 ID 的painterResource
- amazon-web-services - 为什么 RStudio 服务器正在运行我的闪亮应用程序,但该应用程序没有显示在 aws ec2 实例上的闪亮服务器中?
- c# - Xamarin Forms:尝试为 Android 构建条件格式,错误:System.InvalidCastException Message=Object must implement IConvertible
- css - TypeError:无法读取类绑定上的 vue 绑定对象属性的未定义属性
- javascript - 当浏览器中没有垂直滚动时,div被剪切
- nginx - NGINX 中的映射别名
- reactjs - 如何使用 React Native Paper Fab 获得圆形按钮
- python - python2到python3修改源码过程中出现的问题
- windows - “抱歉,此文件无效,无法显示。” 在 GIthub 上使用 pdf 文件
- xcode - 如何在cordova项目中通过config.xml更改ios xcode“Packaging”->“Product Name”?