Looking for Precise Matching within JSON Using JavaScript

I've been experimenting with creating a form that submits data and then checks it against a JSON array to see if there's a matching object already present. Here is a snippet of my JSON data for reference:

[
{
    "ASIN":"B0971Y6PQ3",
    "price":"13.99",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="106475636450777d71797c3e737f7d">[email protected]</a>"
},
{
    "ASIN":"B077TLGP58",
    "price":"13.99",
    "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e4f5e3e4d0f7fdf1f9fcbef3fffd">[email protected]</a>"
}
]

I am currently working on a loop that will examine whether the form data matches any existing JSON objects. Here is the code I have so far:

// Check if it exists in asinJSON.json file
for(i=0; i<asinJSON.length;i++){
    if(asinJSON[i].email == email){
        // Email already in the json
        if(asinJSON[i].ASIN == inputVal){
            // Email and ASIN already in json
            if(asinJSON[i].price == desiredPrice){
                // Matching email, ASIN, and price. Duplicate.
                console.log('same price found. product already exists.');
                break;
            }
            // Price does not match, user wants to update
            console.log('updating price');
            // Update price functionality here
            // updateJSON();
            break;
        }
        // Existing user wants to add new product
        console.log('product not found');
        // Insert new product for existing user
        // createAndAdd();
        break;
    }
    // New user wants to add a product
    console.log('email not found');
    // Insert new product for new user
    // createAndAdd();
    break;
}

Currently, when attempting to find the second object, the console logs "product not found," likely due to passing the first IF statement but failing the second one with the 1st object in the array.

I suspect there may be an issue with my break statements. I've also tried return statements without success. As a self-taught developer, I acknowledge that I may have missed some key concepts along the way. Despite searching on Google and StackOverflow, I haven't been able to find a solution, so I'm reaching out here for help.

I'm eager to learn how to properly structure this logic for it to function correctly. Any feedback is greatly appreciated!

Answer №1

Utilize the find() function to look for a corresponding element.

if (inventoryData.find(({itemID, cost, email: jsonData_email}) => 
    itemID == userInput && cost == requestedPrice && jsonData_email == userEmailAddress)) {
    console.log("Item already in stock");
} else {
    console.log("Item not found in inventory");
}

Answer №2

There are numerous choices available, but one convenient method involves utilizing the lodash library

const email = <email input>
const price = <price input> (however, be cautious when dealing with floating point comparisons...)
const ASIN = <ASIN input>
if (findIndex(asinJSON, { ASIN, price, email }) > -1) {
   // item discovered
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for preventing the creation of an element in AngularJS

When working with Angular, I encountered an issue with creating an <iframe> element only upon user interaction. Initially, I simply placed the element on the page and used the ng-if directive to bind its presence to a boolean in my model. However, I ...

Update the div element without needing to reload the entire page

Is there a way to reload a div tag without refreshing the entire page? I understand this question has been asked before, but I want to make sure I have a clear understanding. <p>click HERE</p> <div class="sample"> <?php functi ...

Different methods of transferring PHP post information to JavaScript

Is there a cleaner and more elegant way to pass posted PHP variables to JavaScript for manipulation, rather than using inline JavaScript? I currently have a simple PHP form that posts data to specific variables and then uses inline JavaScript to handle the ...

React - Unable to perform 'removeChild' on 'Node' object: The specified node cannot be removed as it is not a child of this node

I am encountering an issue in my React project with the following structure: <div className="App"> <BrowserRouter> <BasicLayout title={"test"}> <Routes> <Route path="/home&qu ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

What is the best way to update the displayed data when using Mobx with an observable array?

Is there a way to re-render observable array data in Mobx? I have used the observer decorator in this class. interface IQuiz { quizProg: TypeQuizProg; qidx: number; state: IStateCtx; actions: IActionsCtx; } @observer class Comp extends Rea ...

The callbacks in NextAuth do not appear to be functioning

I am currently working on implementing authentication with NextAuth in my Next.js app. I've noticed that the callbacks from the GoogleProvider are not being executed. Even after adding a console log statement, I cannot see any output in the console. A ...

Error in Javascript: Null Object

I have created an upload page with a PHP script for AJAX, but I'm encountering errors in Firebug. Also, the upload percentage is not being returned properly. Currently, I can only do one upload in Firefox and the script doesn't work in Chrome. H ...

Mastering ReactJs: The Ultimate Guide to Updating State Properties

I've been attempting to change the isSelected property for a specific row in my state data, but am finding that it's not updating. Can someone please offer guidance on the most effective approach to achieve this? var selecte ...

Is there a way to create a clickable component for triggering an AJAX call without using a Submit button?

Just starting out with JS/JQuery programming, so please excuse any mistakes or unclear explanations. Any feedback is welcome, even if not requested specifically. I am working with multiple drop down lists that are populated dynamically by data from SQL Ta ...

Discovering the key and corresponding value within a JSON object based on a different key-value pair

I am currently working in PostgreSQL and I'm attempting to extract the key (r_dirigeant, r_actionnaire, r_beneficiaire) or generate a text containing all keys when "r_ppe" = "oui" and one of the keys (r_dirigeant, r_actionnaire, r_beneficiaire) is als ...

Is it feasible to deliver a push notification on iOS without utilizing the "alert" attribute in a JSON payload?

Is there a way to send a JSON format without including the "alert" attribute and still have the notification appear? I've attempted to remove the alert attribute, but it seems to prevent the notification from showing up. Any suggestions on how to hand ...

Ensure that the number is valid using Express Validator in Node.js

One thing that I've noticed when using express validator is the difference between these two code snippets: check('isActive', 'isActive should be either 0 or 1').optional({ checkFalsy : false, nullable : false }).isInt().isIn([0, 1 ...

Having trouble with Discord.js version 12 and the messageReactionAdd event not triggering properly?

client.on('messageReactionAdd', (reaction, user) => { console.log('If you see this I actually work...'); }); I am having some trouble with my code. Despite setting up a simple console log, it seems like the code is not running prope ...

Working with Array of Objects Within Another Array in Angular 6 Using Typescript

I'm currently working with an array of "food": "food": [ { "id": 11, "name": "Kabeljaufilet", "preis": 3.55, "art": "mit Fisch" }, { "id": 12, "name": "Spaghetti Bolognese", "preis": 3.85, "art": "mit Fleisch" }, { "id": 1 ...

Identifying when a page-loading or reloading event has been canceled

When the Cancel button is pressed during page load/reload, the content of the page loads partially. Is there a more effective way to address this issue rather than displaying incomplete content? For instance, consider showing a message such as "Page load ...

`I'm encountering issues when trying to pass an array through localStorage into a new array`

This is a complex and detailed question that I am struggling to find a solution for. Despite using deprecated mysql due to hosting limitations, the problem lies elsewhere. Part 1 involves dataLoader.php, which queries the database and retrieves posx and p ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

Tips for inserting a Vue.js variable into a window.open event

Within this snippet of code: <tr v-for="person, index in People" :key='index'> <td> <button type="button" onclick="window.open('/details/'+person.id,'_blank')"> details</butto ...

Is there a way for me to determine the quality of a video and learn how to adjust it?

(function(){ var url = "http://dash.edgesuite.net/envivio/Envivio-dash2/manifest.mpd"; var player = dashjs.MediaPlayer().create(); player.initialize(document.querySelector("#videoPlayer"), url, })(); var bitrates = player.getBitrateInfoListFor("vid ...