我一直試圖弄清楚如何提交表單,然后根據 JSON 陣列資料檢查表單中的所有資料,以確定匹配所有輸入的物件是否已經存在。首先,這是我的示例 JSON 資料:
[
{
"ASIN":"B0971Y6PQ3",
"price":"13.99",
"email": "[email protected]"
},
{
"ASIN":"B077TLGP58",
"price":"13.99",
"email":"[email protected]"
}
]
所以我試圖運行一個 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 "product not found",我的理解是因為它通過了第一個 if 陳述句,但在 JSON 陣列中的第一個物件中失敗了第二個.
我還假設它與我的 break 陳述句有關,并且那里出了點問題。我也試過 return statents 并沒有弄清楚。我是自學的,所以不幸的是,我在此程序中肯定錯過了一些東西。但是,我查看了 Google 和 StackOverflow 并沒有真正找到答案,所以我來了。
我已準備好接受如何設定此邏輯以使其正常作業的教育。我提前感謝所有反饋!
uj5u.com熱心網友回復:
使用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");
}
uj5u.com熱心網友回復:
有很多選擇,一種簡單的方法是使用 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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/387526.html
標籤:javascript 数组 json for循环 嵌套循环
