Add more array of objects into a localstorage key

I have a localstorage key 'st' with value:


I want to add one more keyvalue at the end if it doesnt exist so to end up with:


So what I tried was:

if (typeof getstate(json, 'NEWKEY') == "undefined"){
  localStorage["st"] = JSON.stringify([{
     "id": "es",
     "state": getstate(json, "es")
  }, {
     "id": "xs",
     "state": getstate(json, "bs")
  }, {
     "id": "NEWKEY",
     "state": "off"

Where getstate gives me the state for a certain specific id.

Now the main issue is that I want to keep the values as their are (so i need to retrieve them at the time) and use the easiest method so in case my key had 30 different id's and I wanted to add 1 more, I didnt had to retrieve values for all 30 id's.


It seems like you would be a lot better off with an object that uses each ID as a key, not an array of objects

var st={

Then to access data for an ID:


To add a new property:

st['newKey']={state:"off"}/* same as writing st.newKey={state:"off"}
     /* OR*/

Object would then look like:

var st={
  newKey :{state:"off"}/* quotes on object keys are optional unless they contain special characters or spaces*/

You would then convert whole object to and from JSON using JSON.stringify(st) or JSON.parse( localStorage['st'])

Edit: if you prefer keeping array format you can add a new element as follows:

var st = [{"id":"es","state":"5hwrte5"},{"id":"bs","state":"dakiei3"}];

st.push( {"id":"NEWKEY","state":"off"})

/* results in */

Using the array you would have to loop over each element in array to do a search for a specific ID

for(i=0 ; i< st.length; i++){
     var object= st[i];
    if ("NEWKEY"){

Need Your Help

Connect four multithread design - Homework

java multithreading design-patterns

I'm trying to make a connect four game sumulation.

Scala Default Values: How do I get a default value from type Any in Scala while creating a LinkedList?

scala linked-list manifest default-value any

I am creating a Doublelylinked list in Scala and I have having a problem creating the sentinel node. For my sentinel node's data, I need the default value of the type I am using (EX: I need 0 for I...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.