In localStorage how do we save similar tuples with index? - javascript

In our extension, we are getting values of username( eg: Johnny123), accname (eg: Facebook).
I want to store this for multiple accounts and usernames in the localStorage.
We have written this code :
var i = Number(localStorage.usercounter); // counter for number of users
localStorage.username(i) = username.value; // textbox value
localStorage.accname(i) = accname.value; // textbox value
this code is not executing, what is the right way to store the values?
localStorage.username = username.value;
localStorage.accname = accname.value;
this is executing and allowing us to retrieve values. Please Help.

localStorage stores strings on data-properties...
...your options are:
store a JSON representation of an array which contains user objects
var userdata = [{ name : "Bob", account : "Facebook" },
{ name : "Doug", account : "LinkedIn" }],
userjson = JSON.stringify(userdata);
localStorage.setItem("users", userjson);
console.log(JSON.parse(localStorage.getItem("users")[0].name);
store a JSON/string representation to a suffixed key
localStorage.setItem("user_0_name", "Bob" );
localStorage.setItem("user_0_account", "Tumblr");
localStorage.setItem("user_1_name", "Doug" );
localStorage.setItem("user_1_account", "MySpace");
// ...
As you can see, the first option is the one that makes more sense.

This is how I'd read write it using truStorage (https://github.com/andresgallo/truStorage)
truStorage.setItem('a',{});//This will be the main key, the one localStorage is aware of
truStorage.setItem('a.b',[1,2,3]);//Now we can store variable 'b' inside object a
truStorage.getItem('a'); //returns entire object {a : {b: [1,2,3]}}
truStorage.getItem('a.b') //returns child object {b: [1,2,3]}
You can write directly to child items the same way as you suggested.
truStorage.setItem('a.b.c', 'value of third level nested object c');
In the background this really does the JSON parse/stringify and recursion for you, which will clean up you application massively if you are using lots of localStorage.

Related

How to store key value pairs in JavaScript

I'm new to JavaScript and I want a Data Structure for my JavaScript code which stores Student data as key value pairs. The key is the student Registration number and the value is the students name.What I'm thinking is to create a JavaScript object as follows and store data as follows
let Student={
001A:"John",
002A:"Mathew"
};
Is this approach is correct? And if it is correct suppose a way to dynamically add key value pairs to that. Thank you
That would be an object literal. You'd want the key to be a string, but other than that you've basically got it. You can dynamically add properties using bracket syntax. I've attached a small snippet to give you an idea of how it works. :)
let Student={
"001A":"John",
"002A":"Mathew"
};
Student["003A"] = 'Jessica';
Object.entries(Student).forEach(entry => console.log(entry) );
The approach is correct. Given
const students={
'001A': 'John',
'002A': 'Mathew',
};
(Note: It's a good idea to keep your key as a string to prevent collisions with reserved keywords)
To read from the structure you can access the given record via
console.log(students['001A']); // => 'John'
To add new records dynamically, you just add a new property and assign it the desired value:
students['007'] = 'Ben';
which results in
console.log(students);
// =>
{
'001A': 'John',
'002A': 'Mathew',
'007': 'Ben',
};
To delete a given record you can do either
delete students['007'];
or
students['007'] = undefined;
The first option is a little "cleaner" as it completely deletes the given key, along with its assigned data.
Keep in mind that the data will be removed once you reload the page.

JQuery Mobile JSON Stringify

I'm new in jquery mobile. I'm doing a shopping list application for my school assignment and I'm requested to store objects in local storage.
Each item must include the following information: item Name, item quantity and a Boolean is_bought.
I wish to store all items data into one JSON string. Items data is entered by user from an other page.
My problem is
1)How items can be stored in local storage through JSON stringify.
2)How items data can be retrieved from JSON string to be represented into a list.
First: If I understood you right you have an object(json) structure like:
{
"name": "cheese",
"quantity": 2,
"is_bought": false
}
If not (in question you have no key(name) for your variables) your structure must be like I showed for having an access to each variable in the object.
Second: About localStorage. It is limited to handle only string key/value pairs, so you can't just save an object in it. You have to use JSON.stringify() to parse your object into the string and save in localStorage, then, after retrieving, use JSON.parse() to parse it back. The code could look like this:
var item = {"name": "cheese", "quantity": 2, "is_bought": true};
// Store item into localStorage
localStorage.setItem('item', JSON.stringify(item));
// Retrieve item from localStorage
var retrievedItem = localStorage.getItem('item');
var parsedItem = JSON.parse(retrievedItem);
EDIT: TO STORE MULTIPLE ITEMS
So, if your question is about storing multiple items and distinguishing them, and if your item's name is unique and you know what item is bought, you can store them into the localStorage with the key of item's name, e.g.
// You can do this in a for loop
localStorage.setItem('item_' + item.name, JSON.stringify(item));
// And to change (if you already know bought item's name), 'cheese' for example
var retrievedItem = localStorage.getItem('item_cheese');
var parsedItem = JSON.parse(retrievedItem);
parsedItem.is_bought = true;
// And save again in localStorage
localStorage.setItem('item_cheese', JSON.stringify(parsedItem));

localStorage array of objects handling

Array of JSON objects are stored in HTML5 localStorage.
For now delimiter is ;
For accessing and modifying array of objects from localStorage, split(';') and join(';') operations used.
However ,delimiter approach looks unstable.
For instance ; could be met inside objects attribute and split(';') operation will be uncorrect.
It could be used ;; for delimiter,but i'm not certain it will be stable also.
Is there any robust way to handle localStorage presented as array of objects,as far localStorage saved as String?
EDIT
one of stoppers is that array of object couldn't be saved to localStorage as classical: "[{},{}]"
localStorage converts it automatially to String like "{},{}"
my current data within localStorage:
"{"name":"volvo","id":"033"};{"name":"saab","id":"034"}"
assumption
perhaps,i can add [ at the start and ] at the end,but it looks not gracefull
Just convert the objects to JSON strings:
localStorage.setItem("savedData", JSON.stringify(objects));
And vice versa:
objects = JSON.parse(localStorage.getItem("savedData")));
Or you can add multiple objects in the same localStorage value:
localStorage.setItem("savedData", JSON.stringify([object1, object2 /*, etc*/]));
object1 = JSON.parse(localStorage.getItem("savedData"))[0];
object2 = JSON.parse(localStorage.getItem("savedData"))[1];
Here's the DOM storage specification.
You can also access savedData like this:
localStorage.savedData = "Hello world"
var foo = localStorage.savedData;
This can be used for both getting and setting the data, but it is considered less "safe" than getItem('name'); and setItem('name', 'value');
Read variables:
var xyz = JSON.parse( localStorage.getItem( 'element' ) );
Store variables:
localStorage.setItem( 'element' , JSON.stringify(xyz));
where element is the name of the local storage variable and xyz the name of the js variable.

storing and retrieving json objects to / from a cookie

Im attempting to store json objects in a cookie, but im running into a few problems.
I can create my object like this:
product = {
"name" : "prodname",
"quantity" : 4
}
i then save this object in my cookie. As more products are added (its a shopping basket) i add further strings by appending new objects onto the end of the cookie string (so i essentially have lots of small seperate objects) . Im having trouble getting the objects back out of the cookie string though. Both $.parseJSON and eval fail when i attempt to read the objects back from the cookie. Any help would be appreciated.
its not a good practice to save the value that returned from JSON.stringify(cookieStr) to the cookie. it can lead to a bug in some browsers.
before using it you should convert it to base64 (using btoa), and when reading it, converting from base64 (using atob)
val = JSON.stringify(cookieStr)
val = btoa(val)
write_cookie(val)
It should probably be like:
{"products": [
{
"name" : "prodname",
"quantity" : 4
},
{
"name" : "prodname2",
"quantity" : 3
}
]}
The [] signifies an array. When you want add another product, you load it from the cookie, update the array, then save it again. If you wanted, you could skip the outer object and have the cookie just be the array.
EDIT: Say cookieStr is your cookie.
var root = $.parseJSON(cookieStr);
root.products.push(newProduct);
cookieStr = JSON.stringify(root);

How to store temporary data at the client-side and then send it to the server

I need to store data temporarily at the client-side to allow users to add, edit or delete items without having to query the server for each of these actions; just when the user finishes adding items and clicks on the Add button, the list is sent to the server to be saved permanently.
This image describes what I want to achieve.
I know I have to use arrays in JavaScript, but I don't know how to create one to store objects (in this case Detail which contains :id, price and description).
I hope you can help me out.
Thanks in advance.
PS: I'm using JSP and... sorry for my English
Sure, since it's a table it makes sense to have an array of objects. Note that an object is surrounded by curly braces and an array is surrounded by brackets:
var myArray = []; // Initialize empty array
var myObject = {}; // Initialize empty object
This should accomplish what you need:
// Initialize variables
var newEntry, table = [];
// Create a new object
newEntry = {
id: '',
price: '',
description: ''
};
// Add the object to the end of the array
table.push(newEntry);
Which is the same as this:
// Initialize array
var table = [];
// Create object and add the object to the end of the array
table.push({
id: '22',
price: '$222',
description: 'Foo'
});
You can now access properties like this:
table[0].id; // '22'
On modern browsers, if you want the data to persist across sessions (like cookies) you could use the sessionStorage or localStorage objects.
When you want to send the data to the server, you'll send a JSON version of the table across the wire:
var data = JSON.stringify(table);
You can create an Array of your custom Detail objects pretty easily with object literals:
var details = [];
details.push({id:'abc1234', price:999.99, description:'Tesla Roadster'});
details.push({id:'xyz5678', price:129.99, description:'Land Rover'});
Then you can post your data to the server when the user clicks "Add."
Sounds like a good job for JSON.

Categories

Resources