【发布时间】:2022-01-21 16:07:55
【问题描述】:
我一直试图弄清楚如何提交表单,然后根据 JSON 数组数据检查表单中的所有数据,以确定是否已经存在与所有输入匹配的对象。首先,这是我的示例 JSON 数据:
[
{
"ASIN":"B0971Y6PQ3",
"price":"13.99",
"email": "test@gmail.com"
},
{
"ASIN":"B077TLGP58",
"price":"13.99",
"email":"test@gmail.com"
}
]
所以我正在尝试运行一个 for 循环,该循环将测试所有表单数据是否已经作为 JSON 对象存在。这是我目前拥有的:
// Check to see if it's already in asinJSON.json
for(i=0; i<asinJSON.length;i++){
if(asinJSON[i].email == email){
// Email is already in json
if(asinJSON[i].ASIN == inputVal){
// Email && ASIN are already in json
if(asinJSON[i].price == desiredPrice){
// Email, ASIN, Price all match. Duplicate.
console.log('same price found. product already exists.');
break;
}
// If price doesn't match, user wants to update price
console.log('updating price');
// Update price here
// updateJSON();
break;
}
// Existing user wants to add new product.
console.log('product not found');
// Insert product for existing user
// createAndAdd();
break;
}
// New user wants to add a product.
console.log('email not found.');
// insert product for new user
// createAndAdd();
break;
}
现在情况如何,在尝试测试是否可以找到第二个对象时,它 console.logs “找不到产品”,我理解这是因为它通过了第一个 if 语句但第二个失败了,第一个对象在JSON 数组。
我还假设它与我的 break 语句有关,并且那里有问题。我也尝试过退货声明,但无法弄清楚。我是自学成才的,所以不幸的是,在此过程中我肯定错过了一些事情。但是,我查看了 Google 和 StackOverflow 并没有真正找到答案,所以我在这里。
我已准备好学习如何设置此逻辑以使其正常工作。提前感谢所有反馈!
【问题讨论】:
-
只要第一个数组元素不匹配,您就会打印
not found。这样做之后你就崩溃了,所以你永远不会继续寻找匹配的元素。 -
^ 使用
continue而不是break并且现有代码应该可以正常工作
标签: javascript arrays json for-loop nested-for-loop