Find if a specific pair of values exist in an array of named objects in localStorage with JS

Viewed 65

In localStorage I set previously various objects which are stored in this format

console.log(localStorage) 
// Outputs the storage this way, it may contain different objects (randid for example)

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

I try to find if a specific pair exists in this array of objects for example

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

My code which does not do what I expect

var data = JSON.parse(localStorage) // I tried and without Parsing it as JSON

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

If you want to go through all the values stores in your local storage. You will have to do the following:

  1. Get all the values using Object.values, and start filtering them one by one
  2. Try to parse them as JSON object, some will fail because they are not JSON object, those are not of our interest
  3. Those that parsed successfully, you need to check the key and see if the value for that key matches properly as in matches in type as well as value. Return true so that we can be done with our search and the value is stored in a variable.

Also, please note when you are comparing values use === and not = in your if statements as you have shown in your question. Also, take care types when comparing. You are setting ABA as a number but you are trying to compare with a string.

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

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

// This will 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));

// This will 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));

You have to parse the stored object in the localStorage, because it is stored as a string.

for (var key in localStorage) {
  try {
    const value = JSON.parse(localStorage[key]);
    if (value.ABA == "876346545") {
       var m = localStorage[key];
       console.log("Found: ", m)
       break;
    }
  } catch(e) {
    continue;
  }
}
Related