Determine the presence of a particular set of values within an array of named objects stored in the browser's localStorage using JavaScript

Previously, I stored various objects in localStorage in the following format:

console.log(localStorage) 
// The storage output may vary, with different objects (such as randid)

Storage {
    876346545: "{"ABA":"876346545","ABB":"37578533567","ABC":"AE123456","ABD":"1234567890123456"}", 
    randid: "fhjidc06om230j2r367gh1i5iec", 
    353446545: "{"ABA":"353446545","ΑBB":"12343212341","ΑBC":"CC949590","ABD":"5943949562340543"}", 
    length: 3
}

I am attempting to check if a specific pair exists within this array of objects.

 //Pseudo-code
 if anyofObject in localStorage contains pair ("ABA":"876346545") return true or false

The code I'm using isn't behaving as expected

var data = JSON.parse(localStorage) // I've also tried without parsing it as JSON

for (var key in data) {
    if (data[key].ABA = "876346545") {
        var m = data[key];
        console.log("Found: ", m)
        break;
    }
}

Answer №1

If you wish to iterate through all the values stored in your local storage, follow these steps:

  1. Retrieve all values using Object.values and filter them one by one
  2. Attempt to convert them into JSON objects; those that fail are not of interest
  3. For successfully parsed values, check if the key matches both in type and value. Once a match is found, return true to complete the search and store the value in a variable.

Remember to use === for value comparisons, not =, as depicted in the question. Pay attention to data types when making comparisons; for instance, setting ABA as a number but trying to compare it with a string.

userData = {
  "ABA": 876346545, 
  "ABB": 37578533567, 
  "ABC": "AE123456", 
  "ABD": 1234567890123456
};

localStorage.setItem("Some Random Key", JSON.stringify(userData));

// Find the object and store it in foundObject variable
const foundObject = Object.values(localStorage).find(v => { 
  try { 
    return JSON.parse(v).ABA === 876346545; 
  } catch(e) {
    return false;
  };
});

console.log(JSON.stringify(foundObject));

// Find the object and store true if found, false if not found in hasObject variable
const hasObject = Object.values(localStorage).some(v => { 
  try { 
    return JSON.parse(v).ABA === 876346545; 
  } catch(e) {
    return false;
  };
});

console.log(JSON.stringify(hasObject));

Answer №2

To access the information stored in localStorage, you will need to parse the object as it is saved as a string.

for (let item in localStorage) {
  try {
    const data = JSON.parse(localStorage[item]);
    if (data.id === "876346545") {
       let result = localStorage[item];
       console.log("Located Data: ", result)
       break;
    }
  } catch(error) {
    continue;
  }
}

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

Selecting JavaScript file on change as default option

Currently, I have an HTML file that prompts the user to select an XML file when the file selection is changed. Is there a way to make it so that by default, only one file is chosen? <form id='fileSelection' action=""> <center> <in ...

Using ng-style to apply a background image with a dynamic id

Hey there, I'm facing an issue here. The link provided below seems to not be working properly. Even though the id is set correctly within the scope, it seems like there might be a parsing error occurring. Any thoughts on what might be causing this pro ...

Can you explain the distinction between querying a database and making a request to an endpoint?

Recently, I've been diving into learning mongoose but came across a code that left me puzzled. I'm curious as to why we include the async keyword at the beginning of the callback function when querying a database. Isn't it already asynchron ...

Issue with displaying options in Angular2 v2.4.9 HTML select element

Ever since I made the transition from AngularJS to Angular2, I've been facing a peculiar issue. The select element's options data is fetched from a Solr query, which always returns a 200 response with the data in a timely manner. However, the pr ...

"Uncaught ReferenceError: Rawdata.some is not defined, and a table design

Currently, I am in the process of developing a basic table using data retrieved from the backend via an API call with Ant Design in React. The version of Ant Design I am using is: "antd": "^5.1.1", My approach involves making an API ...

Having trouble retrieving the tag name, it seems to be giving me some difficulty

I have two separate web pages, one called mouth.html and the other nose.html. I want to retrieve a name from mouth.html and display it on nose.html when a user visits that page. How can I accomplish this using JavaScript? Here is the code snippet from mou ...

Storing the selected value from a dropdown box in PHP

Can anyone help me with echoing the $row['price'] based on the user's GPU selection? Your input is greatly appreciated! #adding more content to meet word count requirements. <div id="content"> <table border="1" style="width: ...

Locate the highest value in every row within a numpy array, along with the matching element in a separate array of equivalent size

As a newcomer to Python, I am still working my way towards becoming a proficient Python programmer. Please pardon me if my question seems unclear. Question: I have two numpy arrays, A and B, of the same size with dimensions (5,1000). I am looking to find ...

Leveraging the replace feature within Selenium IDE

After extracting information from a webpage, I found a string that read "price: $30.00" which I saved as "x." What I really needed was just the numbers - "30.00". I attempted to use x.replace(), but unfortunately it didn't work out. If anyone could as ...

Create a pointer/array for an unnamed struct and set it as

struct A { int member1; int member2; struct B { int member3; int member4; } *b; }; Is there a way to successfully initialize A while simultaneously creating an array of Bs to populate the b field? I need a static variab ...

Converting hierarchical JSON data into a table with rowspan using Angular

I am facing a challenge in creating a table using nested JSON obtained from an API. I am unsure how to dynamically merge cells when needed, especially since the JSON structure can be nested up to 6 or 7 levels. Desired Table : Expected Table Current Ou ...

Oops! It seems that an invalid BCrypt hash triggered an unspecified "error" event that was not handled

Attempting to develop an API for login in nodejs. However, when checking the login route via HTTP requester, nothing is displayed in the output. Instead, the command line shows an error Error: Uncaught, unspecified "error" event. (Not a valid BCrypt hash.) ...

Using the ++ operator in a recursion to print elements backwards may skip the first element of the array

When attempting to print an integer array backward using ++ instead of "startPos + 1", I noticed that the first element of the array is lost. I tried debugging to understand the issue, but the recursion behavior seems odd. Can you please explain what the ...

Angular logs the HTTP error before it is processed

When a user clicks on a button on a simple login form, a mechanism is triggered. This mechanism involves sending a POST request to a REST service with the user's provided credentials. If the credentials are correct, the success function is executed, o ...

What is the method for smoothly transitioning the vertical flip of an image within its current position using CSS?

Can someone help me figure out how to smoothly flip my image vertically using rotateX after a few minutes at its center position? The image is flipping, but not on its actual center. It seems to be rotating from a point above the image. I've tried adj ...

Unable to reach deeply nested objects and arrays within an EJS template

Hello everyone, I am attempting to retrieve the response mentioned in the link for my EJS template. At the moment, I have a for-loop that goes through all the campaigns. campaigns.facebook.data[i].insights .data I have tested the following code which se ...

Utilizing AngularJS to display a table with Rowspan functionality and the ability to filter elements

I am trying to develop an HTML table that utilizes rowspan with ng-repeat to group data effectively. The overall layout is functioning as expected, but I encountered a problem when attempting to apply filters to the table. Specifically, when I filter the ...

Checking for disconnection in Vue.js

On my Laravel / Vue.js website, I'm trying to figure out how to detect when the connection to the server is lost and display a warning message on the front end. I've come across using axios for this purpose, but I'm unsure of where exactly ...

Ways to apply the .not selector efficiently in jQuery

I have a situation with two separate divs, one named task1 and the other named task2. Each of these tasks contains panels with various names. Within task2, there is a duplicate name (Greg), who also belongs to the duplicate class. I'm trying to figure ...

Template with a modal overlay

After clicking a button, I want a modal window to appear. However, if the button is inside a template-generated page, the modal window does not appear. <script type="x-template" id="company-template"> <button class="ui but ...