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

Is above json structure good for storing says users viewed books? I have other key like users' setting so I try to nested/group things to be neater. My question is how can I check an object with value exist or not so I won't insert duplicated data. How to check the id 2 is existed in this case? Do I have to loop?

Elton Jamie
  • 586
  • 6
  • 17

1 Answers1

0

Do I have to loop?

Yes you have to loop ( or use a method which will do it) :

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


//do whatever with `wasFound`.

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

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • I saw some push example that doesn't check like this, how do they handle possible of inserting duplicate entry into localstorage? – Elton Jamie Mar 22 '15 at 07:48
  • @EltonJamie where is the link for that ? – Royi Namir Mar 22 '15 at 07:55
  • maybe this is different case, because they don't use nested json like mine http://stackoverflow.com/questions/20936466/cannot-push-objects-in-array-in-localstorage – Elton Jamie Mar 22 '15 at 07:57
  • No. `setItem` inserts if not found and update if found. but it works by key , you can't do : "update key "JOHN" if "JOHN" is found with value 5. see [here](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem) – Royi Namir Mar 22 '15 at 08:00
  • Ya that's keys, I'm trying to store many things in one key, right? – Elton Jamie Mar 22 '15 at 08:20