【问题标题】:Search For Exact Match In JSON With JavaScript使用 JavaScript 在 JSON 中搜索精确匹配
【发布时间】: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


【解决方案1】:

有很多选择,一个简单的方法是使用 lodash

const email = <email to find>
const price = <price to find> (however, keep your mind around floating points comparison here...)
const ASIN = < ASIN to find >
if (findIndex(asinJSON, { ASIN, price, email }) > -1) {
   // found
}

【讨论】:

    【解决方案2】:

    使用find() 方法搜索匹配元素。

    if (asinJSON.find(({ASIN, price, email: json_email}) => 
        ASIN == inputVal && price == desiredPrice && json_email == email)) {
        console.log("product already exists");
    } else {
        console.log("product not found");
    }
    

    【讨论】:

    • 啊。非常感谢巴尔玛。我在寻找解决方案时看到了 find(),但因为它只返回匹配的第一个元素而被推迟。我错误地考虑在 for 循环中使用它,而不是在 for 循环中使用它。我会尝试一下。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 2013-07-19
    • 2022-01-19
    • 1970-01-01
    • 2013-08-15
    相关资源
    最近更新 更多