0

My Google Chrome extension uses JSON.parse(oldJSONstring) to create an object with configuration information. The "oldJSONstring" was saved from previous sessions on Chrome's localStorage.

As I sometimes add new features, after I create the new object, I manually validate that all configuration entries exist, if not, I'll set them with default values. This is done, in case it's he firs time a user loads the extension after it updated.

I was trying to think of a more automatic way of doing this, like using a JSON Schmea, but I really don't know where to start, and my first round of google searches didn't produce anything I could use.

Another approach I thought was to iterate on all my Default settings -also stored on a JSON object- and then confirming they exist on the new object... but I just realized I don't know how to iterate a JSON object for all its attributes :)

The end goal of this is that I'd like to forget about validating for new attributes, every time I create a new feature and I publish a new version... does it make any sense? does it make me lazy? :D

Thanks!

frenetix
  • 1,199
  • 1
  • 11
  • 19
  • 1
    A very easy solution would be to have all the default values hard-coded into one object and once the plugin loads you merge the object containing the user-specified options into the one containing the default values. So for all none-specified values the default values are used. If you are using a jQuery you can use `extend` with the first parameter being set to `true`. – clentfort Oct 27 '12 at 22:33

2 Answers2

2

Keep the default object handy and use jQuery $.extend to merge the 2 objects.

var defaults={ color:'blue', size:'Large'}

var chromeObj= /* code to grab from storage*/
/* update chromeObj with all key/value pairs in defaults */
 /*  regardless if they already exist or not*/
$.extend( chromeObj, defaults}

/* code to put chromeObj back to storage*/

Refrence: http://api.jquery.com/jQuery.extend/

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • 2
    @frenetix This answer can be even simplier: The one-liner `$.extend({}, defaults, chromeObj)` does what you want. – Rob W Oct 28 '12 at 20:20
1

There is no such thing as a "JSON object,"* but it's quite easy to loop over a Javascript object's properties: How do I loop through or enumerate a JavaScript object?

* JSON is just a string format, and it's a subset of Javascript object notation

Community
  • 1
  • 1
jonvuri
  • 5,738
  • 3
  • 24
  • 32
  • Thanks for the correction, and that link looks like what I meant about iterating over my object. After taking a look though, I'll probably go with the jquery extend approach. Thanks! – frenetix Oct 28 '12 at 00:33
  • then again... it will force me to load jquery together with the background script, which I haven't had the need for until now... mmmm :) will see – frenetix Oct 28 '12 at 00:37