Create key value pair array in JavaScript on run time

Posted: August 13, 2015 in Javascript

Below is one simple function that saves my required json in localstorage using JavaScript array.

function saveMyJson(key,value)

// initialise array
var myObj = {};

// get existing json from local storage
if(localStorage.getItem('my_json') != null)
myObj = JSON.parse(localStorage.getItem('my_json'));

// add element in json by key-value pair
eval("myObj['" + key + "'] = \""+ value + "\"; ");

// set updated json in local storage
localStorage.setItem('my_json', JSON.stringify(myObj));




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s