localStorage problems - javascript

My store uses localStorage to store the cart. I've used this line to retrieve the value:
var kamat = window.localStorage.getItem("simpleCart_items"); alert(kamat);
This will retrieve something like :
{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Valkoinen hiilikuitu -teippi","size":"Tyhjä"},"SCI-3":{"quantity":1,"id":"SCI-3","price":4,"name":"Car Speaker -hajuste","color":"Sport Fresh"}}
And as I've stored it as a variable, I want to use it a bit later.
I want to add this before the final curly bracket (after variable kamat)
var toimituskulut = {"Toimitus":{"quantity":1,"id":"Toimituskulut","price":8,"name":"Toimituskulut"}};
I've tried this as it needs a colon between the items:
var kamatjatoimituskulut = kamat + "," + toimituskulut;
But won't work. And if it would, it would insert the contents of toimituskulut after the final curly bracket. So what would I need to do?
EDIT
I'm trying to edit it when a button is clicked:
$("#posti").live('click', function() {
$(".maksu").slideDown(600);
$("#posti").attr("disabled" , "disabled");
$("#matkahuolto").removeAttr("disabled");
$("#posti").addClass( "selectedtoimitus" );
$("#matkahuolto").removeClass( "selectedtoimitus" );
$(".simpleCart_shipping").html(kamat);
var kamatObj = JSON.parse(localStorage["simpleCart_items"]);
kamatObj['toimituskulut'] = toimituskulut;
localStorage["simpleCart_items"] = JSON.stringify(kamatObj);
});
But no, it won't add a thing.
JSFIDDLE
So, if the local storage looks like this:
{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Valkoinen hiilikuitu -teippi","size":"Tyhjä"},"SCI-3":{"quantity":1,"id":"SCI-3","price":4,"name":"Car Speaker -hajuste","color":"Sport Fresh"}}
I want it to look like this when I click a button
{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Valkoinen hiilikuitu -teippi","size":"Tyhjä"},"SCI-3":{"quantity":1,"id":"SCI-3","price":4,"name":"Car Speaker -hajuste","color":"Sport Fresh"},"Toimitus":{"quantity":1,"id":"Toimitus","price":5,"name":"Toimituskulut"}}
But doing var kamatjatoimituskulut = kamat + "," + toimituskulut;
would only output something similar to this, right?
{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Valkoinen hiilikuitu -teippi","size":"Tyhjä"},"SCI-3":{"quantity":1,"id":"SCI-3","price":4,"name":"Car Speaker -hajuste","color":"Sport Fresh"}},"Toimitus":{"quantity":1,"id":"Toimitus","price":5,"name":"Toimituskulut"}

If you have two variables containing JSON strings, like this:
var kamat = '{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Valkoinen hiilikuitu -teippi","size":"Tyhjä"},"SCI-3":{"quantity":1,"id":"SCI-3","price":4,"name":"Car Speaker -hajuste","color":"Sport Fresh"}}';
var toimituskulut = '{"Toimitus":{"quantity":1,"id":"Toimituskulut","price":8,"name":"Toimituskulut"}}';
you'll need to parse those strings into json like so (I'm using jQuery):
var kamatJSON = $.parseJSON(kamat);
var toimitusJSON = $.parseJSON(toimituskulut);
and then add them together like so:
$.extend(kamatJSON, toimitusJSON);
and since it's an object, the order should'nt really matter if you access the values like:
kamatJSON.Toimitus
FIDDLE;

What you want is to add a property to an object.
But what you have is a string, as localStorage only stores strings. It seems to be stored as JSON (which is the most obvious solution).
First you need to restore the object :
var kamatObj = JSON.parse(localStorage["simpleCart_items"]);
Then you may add a property :
kamatObj['toimituskulut'] = toimituskulut;
And then you may serialize it as string again to put it back in localStorage :
localStorage["simpleCart_items"] = JSON.stringify(kamatObj);

Try This :
$("#posti").live('click', function() {
$(".maksu").slideDown(600);
$("#posti").attr("disabled" , "disabled");
$("#matkahuolto").removeAttr("disabled");
$("#posti").addClass( "selectedtoimitus" );
$("#matkahuolto").removeClass( "selectedtoimitus" );
$(".simpleCart_shipping").html(kamat);
var kamatObj = JSON.parse(localStorage["simpleCart_items"]);
var resultObject =JSON.parse((kamatObj).concat(JSON.parse(toimituskulut));
alert(resultobjcet);
localStorage["simpleCart_items"] = resultObject;
});

If you are trying to add content to an object (stringified of course), in local storage, I wrote a tool just for that purpose. It can set any type of value in local storage, and extract likewise. It can even store values nested deep within the stored values. You can find the script/tool here at https://github.com/andresgallo/truStorage

You might want to look at localDataStorage. It transparently sets/gets Arrays, Booleans, Dates, Floats, Integers, Strings and Objects. It provides lightweight data obfuscation (for security) and intelligently compresses strings. The utility lets you query by key (name) or (key) value or data type, checks for duplicate values, and supports the notion of write-protected keys. Note: I am the author of the utility.

Related

Split string using regex expression

I need to split a dynamic string. The string may look like the one below having Code, Name and EffectDate. or it may have only (Code and Name) or (Code and EffectDate) or (Name and EffectDate). You got the point right.
{"Code":{"value":"1"},"Name":{"value":"Entity1"},"EffectDate":{"value":"23/11/2016"}}
to
...
this.data[0].key ='Code'; \\something like this (desired result)
this.data[0].value = '1';
this.data[1].key = 'Name';
this.data[1].value = 'Entity1';
this.data[2].key = 'EffectDate';
this.data[2].value = '23/11/2016';
What i did in my code :
...
filters:string;
data:string[];
...
this.data = this.filters.split("\b(?:(?!value)\w)+[a-zA-Z0-9/]\b");
console.log(this.data);
I used this pattern \b(?:(?!value)\w)+[a-zA-Z0-9/]\b but still couldn't get the desired result. The this.filter always returns only one array with the same string. Any advice would be helpful. Thank you.
Update #1:
I'm using PrimeNg extension for datatable and i get event as a parameter. In that, event.filters returns me a list of filter objects. I cannot send the object to the service, it needs to be in the format to work with the service.
That looks like JSON. What's to stop you from just doing data = JSON.parse(content) and iterating over the key-values using keys(data) for keys and data[i]["value"] for values?
Try something like this:
var data = [];
for(var i in event.filters){
data.push({"key": i, "value": event.filters[i].value});
}

How do I prevent my program from overwriting localStorage every time a button is clicked?

document.getElementById("submit").addEventListener("click", getElements)
function getElements() {
var a = document.getElementById("sample").value;
var x = new obj(a);
function store() {
localStorage.setItem('todays-values', Object.values(x));
}
store();
}
In a separate js file I then call
localStorage.getItem('todays-values');
I get the values, but if I put new inputs into my html file and click the submit button, the previous values get overwritten and replaced by the new ones. How do I store all the values that are submitted and prevent the old ones from getting replaced?
I'm very new to Javascript so I would prefer to solve this problem without the use of any additional libraries if possible.
First: it seems that you are mixing JavaScript a class with a function (here is an example: What techniques can be used to define a class in JavaScript, and what are their trade-offs?)
For example this is the class equivalent in JavaScript:
function ClassName() {
var privateVar;
this.publicVar;
function privateFunction() {}
this.publicFunction = function() {};
}
You shouldn't wrap a function in a function unless it has a meaning (beacuse it is confusing for other people otherwise), but in the example given you don't need that. Also I can't see the reason why you are creating a new object x - if you create the object right before you save it you could just save the value because the object will only contain the value from sample, so you could write something like this:
document.getElementById("submit").addEventListener("click", getElements);
function storeElements() {
var sampleValue = document.getElementById("sample").value;
localStorage.setItem('todays-values', sampleValue);
}
Back to your question:
As Kalamarico mentioned: if you write new values into todays-values you will overwrite your old values, you could simply load all old values from the localStorage append the new ones and write them back to the localStorage.
You should also note that the localStorage only takes strings, so you should stringify objects (see localStorage.setItem).
function appendValueToStorage(key, value) {
var values = JSON.parse(localStorage.getItem(key));
if (values === null) {
values = [];
}
values.push(value);
localStorage.setItem(key, JSON.stringify(values));
console.log(localStorage.getItem(key));
}
appendValueToStorage('todays-values', document.getElementById("sample").value);
The function will let you append some value for a key, you could even wrap this function again to be able to use it in your click function:
function onSubmitClick() {
appendValueToStorage('todays-values', document.getElementById("sample").value);
}
document.getElementById("submit").addEventListener("click", onSubmitClick);
With the console.log command you can see the current content of the localStorage (you could also check with the developer tools - I find the ones for chrome work the best, under the Application -> Local Storage tab you can check the localStorage of your page).
You need read more about localStorage, this is a new feature introduced with HTML5, you can take a look here and see all features.
localStorage stores your data like a JSON object, if you don't know what is JSON, you need to find info. In javascript think in objects in this way:
var myData = {
myName: 'Kalamarico',
myAge: undefined
};
This is a Javascript object, and JSON is very similar and it is a representation of objects.
localStorage API stores your data as this way, when you do:
localStorage.setItem('todays-values', Object.values(x))
localStorage saves a new entry, one key 'todays-values' and its value is an object, so, your localStorage seems:
{
"todays-values": { ... }
}
Every time you set a "todays-values" you will overwrite the key, as you are seeing, so, if you can keep old values, you need to do this manage, first you can get items in localstorage (if there are), and after you can "merge" your old value and the new value. Or you can set a new key, for example: "todays-values1" depends on your need.
If you need to store exactly one key-value pair per day, then you could add the date in the key string.
Else how about numbering the keys ("yourKey_0", "yourKey_1", ...) and also storing the current (biggest) index ("currentIndex")in local storage:
function store(value) {
newIndex = localStorage.getItem("currentIndex") + 1;
localStorage.setItem("yourKey_" + newIndex, value);
localStorage.setItem("currentIndex", newIndex);
}
If you run into problems storing integer values, convert to strings.

Change a json/javascript object var name or retrieve values from a numerical var

I've some page that gives me kinda of a JSON file/output like this
example:
Description:
23463232
tags
appid
35433523
tags
appid
12345234
tags
appid
I'm trying to get the tags values, like so description.23463232.tags
Add gives me this error:
SyntaxError: identifier starts immediately after numeric literal
I know that you all vars must be strings started by letters but I can't change that because this file/page is not mine. So, I'd like to know what can I do to retrieve the tags values or if there is some way to change the name of that vars like "23463232" to something else.
That number is probably a string. You can try using the square bracket syntax for reading JSON like so: description["23463232"]["tags"]
You can use property accessor to access any property name:
description["23463232"].tags
Just for completeness of the answer, if you still need to change the variables, you can do this:
for(var key in description) {
var value = description[key];
//copy the value to a new key (_ prepended) then delete the original key.
description["_"+key] = value;
delete description[key];
}
Now you can access the values like: description._23463232.tags

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.

Javascript is passing an Array of Objects instead of an Array of Arrays

I'm passing a Javascript Array() to Flash via FlashVars but Flash complains. Can you guys point me what am I doing wrong here?
javascript code
// array with the user defined cities
var usercities = new Array(
{'nome':"London", 'lat':51.5002, 'long':-0.1262 },
{'nome':"NYC", 'lat':51.5002, 'long':-0.1262 }
);
flashvars.newcities = usercities;
flash code
// this array is pre-populated so if the users doesn't enter data this is shown
var cities:Array = new Array(
{ nome:"London", lat:51.5002, long:-0.1262 },
{ nome:"NYC", lat:40.7144, long:-74.0060 }
);
// gets FlashVars
var newcities:Object = LoaderInfo(this.root.loaderInfo).parameters.newcities;
if(newcities != null) {
cities = newcities;
};
Doesn't work. I need to have the cities array on the Flash Side exactly as it is. On the Javascript side all code can change.
Thank you for your help.
JavaScript does not have associative arrays like other languages. In order to have named indexes, you have to use an object. An array that is assigned a value with a named index will be converted to an object.
In order to do this, you may need to change your Flash code. As meder said, serializing your array is your best bet. I'd suggest a JSON encode in the JavaScript and a decode in the Flash.
Well you can just manually make them arrays. Something like this:
var usercities = [];
usercities[0] = [];
usercities[0]["nome"] = "London";
usercities[0]["lat"] = 51.5002
usercities[0]["long"] = -0.1262
usercities[1] = [];
usercities[1]["nome"] = "NYC";
usercities[1]["lat"] = 51.5002
usercities[1]["long"] = -0.1262
Though I think it is all the same but flash may be seeing it differently.
Ended up passing the values as this:
javascript
var cities = new Array(
Array("London", 51.5002, -0.1262),
Array("NYC", 40.7144, -74.0060),
);
That flash gets as a pure string.
"London",51.5002,-0.1262,"NYC",40.7144,-74.0060
I then exploded the string and converted to Array. It's a bit dirty but in the end works. As long as the Array always has 3 items per row and no item has a comma.
Hope this may help someone.

Categories

Resources