Ensure that the JSON object exists before saving it to local storage

[
    {
        "id": 1,
        "title": "my First Item",
        "body": ""
    },
    {
        "id": 2,
        "title": "my Second Item",
        "body": ""
    },
    {
        "id": 3,
        "title": "my Third Item",
        "body": ""
    }
]

Do you think the above JSON structure is suitable for storing information about books that users have viewed? I also have other user data to track, so I'm trying to organize things better by grouping them. My main concern is how can I efficiently check if a certain object with a specific value already exists in this structure to avoid inserting duplicate data. For instance, how would I verify whether id 2 is present without having to loop through all the items?

Answer №1

Is looping the only option?

Absolutely, you must loop through the array ( or opt for a method that accomplishes the same) :

var  idToCheck="id";
var  valToCheck=2;
var a = your array...
var wasFound=false;
a.forEach(function(entry) {
   if (entry[idToCheck]==valToCheck) 
    { 
      wasFound=true;
      return;
    }
});


//perform any necessary actions with `wasFound`.

http://jsbin.com/jigefamiqu/1/edit

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

What is the best way to parse a nested json array in PHP?

I am facing an issue with a complex JSON structure that I need to deserialize: [ {"product": {"category_id":1, "created_at":"2015-06-13 17:49:58", "description":"CF77 COIN FINDER", "url_image":"IMG_ ...

Tips for updating a list of orders using keywords entered in a text input field

I have a collection of car objects and an input field that triggers a change event. When the value in the input field is updated, I want to reorganize the order of the cars. For example, if I enter "Tau" in the input box, I want the ford object to be plac ...

javascript mobile nav event

My website utilizes a bootstrap feature for mobile devices where a left sidebar pops up when clicking a button. I am not very familiar with bootstrap, but I would like to link a javascript event to determine if the left sidebar is visible. How can I achiev ...

When attempting to make a post using Prisma's ORM, users may encounter an error message indicating that the post function

Creating a basic prisma application using express and node to query a local mysql database. Encountering an error when calling await prisa.list.create(), details provided below. Here is the script.js code snippet from the HTML page: addItemForm.addEvent ...

Having trouble with the Spotify API showing Error 400 "Invalid JSON Format" in Python?

Hey there! I've been working on a small project in my free time that involves integrating the Spotify API. Everything was going smoothly until I encountered an issue with a specific endpoint on the Spotify API. The problematic endpoint is (you can c ...

Connect CSS Transition to a click action

Below is the code snippet. When you click on the div, it creates a folding effect to the left. You can view it here. I want to link this effect to the arrows I use for sliding back and forth. For example: The left arrow should move the slide to the l ...

Automatically submitting a Google Form using the Google Forms API in conjunction with Google Apps Scripts

Is it possible to integrate a third-party app with Google Forms API and Google Apps Script in order to create timed quizzes that automatically submit once the time limit has been reached? ...

Limit the options in jQuery UI auto-complete to search by name from a variety of JSON responses

I am looking to enhance my search functionality by utilizing jqueryUi's auto-complete feature to specifically target Names and exclude other array values such as fax. Here is how I have implemented it in php: <?php require_once 'db_conx.php&a ...

Is there a way to serialize a C# object to JSON while maintaining the namespace?

The main class includes a property that is replaced by a new property with a different type in the subclass. This has caused an issue during deserialization. I am unable to change the property name in C# or JSON, but I can potentially add a namespace. nam ...

Error: The function $(...).draggable is not recognized" and "Error: The object $.browser is not defined

I encountered an error stating, TypeError: $(...).draggable is not a function. To resolve this issue, I added jQuery as follows: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> < ...

What could be causing the image not to be centered inside the <table><td>?

Currently, I am developing a web application with Google Script that generates a dashboard featuring multiple tables. To design the layout, I am utilizing Bootstrap (https://cdn.jsdelivr.net/npm/[email protected] /dist/css/bootstrap.min.css). Despite ...

CSS - starting fresh with animations

I am facing an issue with a CSS animation that I created. Everything seems to be working correctly, but I need to complete it by setting the input type to reset the animation. Below is the CSS code snippet that should reset the animation: $('button& ...

How to determine if a scrolling action is initiated manually using jQuery

Here is a question that was previously asked long ago: Detect jquery event trigger by user or call by code Despite previous inquiries, a conclusive answer has not been provided (or I may just be inadequate at searching). My query pertains to distinguish ...

Tips for deleting multiple objects from an array in angular version 13

I am facing an issue where I am trying to delete multiple objects from an array by selecting the checkbox on a table row. However, I am only able to delete one item at a time. How can I resolve this problem and successfully delete multiple selected objects ...

Tips for choosing a week on a calendar with JavaScript

Here is the code for my calendar: <script> $(document).ready(function() { var events = <?php echo json_encode($data) ?>; $('#calendar').fullCalendar({ header: { left: 'prev,next', center: &apos ...

The Slide Out Menu functioned properly in HTML, but it seems to be malfunctioning when implemented in PHP

I recently implemented a slide-in and out menu with a hamburger icon to open it and an X icon to close it. The functionality was perfect until I integrated it into PHP and WordPress. Initially, I placed the script in the header section before the meta tags ...

Using <Redirect/> in ReactJS results in rendering of a blank page

Hello everyone, I've been working on a feature where I want to redirect the user to the home page using <Redirect/> from react-router after they have successfully logged in. However, I'm facing an issue where the timeout is functioning corr ...

Tips for formatting the key-value pairs in a JSON object

As a newcomer to nodejs, I have managed to successfully retrieve data from the database and display it as a REST API in key/value pairs. The current output appears like this: [{"id":"793","actionname":"test_bsc_interface","actionid":"100"}]. However, I w ...

"Ensure div remains at the bottom of the page even while

In order to implement a feature where the menu sticks to the top when scrolling down, you can use the following JS code. You can view a live example of this functionality on this Plunker by widening the preview window to see the columns side by side. wi ...

What is the most effective approach to seamlessly conceal and reveal a button with the assistance

I have two buttons, one for play and one for pause. <td> <?php if($service['ue_status'] == "RUNNING"){ $hideMe = 'd-none'; } ?> <a href="#" class="btn btn-warning ...