Add more array of objects into a localstorage key

I have a localstorage key 'st' with value:

[{"id":"es","state":"5hwrte5"},{"id":"bs","state":"dakiei3"}]

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

[{"id":"es","state":"5hwrte5"},{"id":"xs","state":"dakiei3"},{"id":"NEWKEY","state":"off"}]

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.

Answers


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={
  "es":{"state":"5hwrte5"},
  "xs":{"state":"dakiei3"}
}

Then to access data for an ID:

alert( st.es.state);

To add a new property:

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

Object would then look like:

var st={
  "es":{"state":"5hwrte5"},
  "xs":{"state":"dakiei3"},
  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 */
[{"id":"es","state":"5hwrte5"},{"id":"xs","state":"dakiei3"},{"id":"NEWKEY","state":"off"}]

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 ( object.id=="NEWKEY"){
           alert(object.state)
    }
}

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.