-1

I have a local storage, where I stored some Objects. As example product1 and product2. How can I check, if there is already a product2 in my storage? Both object have the same key.

kano
  • 21
  • 5
  • What do you mean by both object have the same key? – Tushar Shahi May 21 '21 at 14:38
  • When you use LocalStorage you must give a key and a value. The objects have the same key but different values. And therefore I want to check if a particular object is already in the storage – kano May 21 '21 at 14:40
  • Does this help you? https://stackoverflow.com/questions/16010827/html5-localstorage-checking-if-a-key-exists – Tushar Shahi May 21 '21 at 14:42
  • unfortunately this is for searching for a key but I need to search for a value – kano May 21 '21 at 14:46
  • If both objects have the same key, then when you add the second one to local storage it's going to overwrite the first one. You are better off making the thing that you want to search by your key, as long as those do not overlap. – hert May 21 '21 at 14:59

2 Answers2

0

Is this what you expect? I am getting all the keys and then checking if my product2 already exists or not. If not then I will set it.

let keys = Object.entries(localStorage);
//let product2, product2; 
let exists = false;
for(let i = 0 ; i < keys; i++){
   if(object[keys[i]] == product2){
     exists = true;break;
}
}

if(!exists) 
  localStorage.setItem("key",product2);

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
0

Have you checked these:

Object.entries(localStorage) //keys
Object.values(localStorage)  // values

You can use it the way you want like this:

Object.entries(localStorage).find(key=>someEvalFn(key))
Soley
  • 1,716
  • 1
  • 19
  • 33