Why do associative arrays don't work in localStorage[""]? - javascript

For example I have the following code:
localStorage["screenshots"] = new Array();
localStorage["screenshots"]["a"] = 9;
alert(localStorage["screenshots"]["a"]);
Arr = new Array();
Arr["screenshots"] = new Array();
Arr["screenshots"]["a"] = 9;
alert(Arr["screenshots"]["a"]);
(I use Google Chrome v9.0.597.107 on Windows Vista 32-bit)
But only the second part works (output of alert() is "a")!
The first alert outputs in contrast "undefined"!
What is the problem?
Thanks.

localStorage stores values as strings, so you need to JSON serialize your objects on the way in and deserialize them on the way out. For example:
var data = {'A': 9};
localStorage['screenshots'] = JSON.stringify(data);
// Later/elsewhere:
var data = JSON.parse(localStorage['screenshots']);
// 9
console.log(data.A);

The localStorage object can only store strings. To store other types of data, use must convert them to strings, and convert them back on retrieval. In most cases you would want to use JSON to do this.

Local storage only stores string keys and string values.
The DOM Storage mechanism is a means through which string key/value pairs can be securely stored and later retrieved for use.
Source: MDC.

Related

When I make a POST request to my back-end and try to access the body, every property is converted to string, including arrays

I just realized that when I make a POST request like this:
async createProduct(){
let formData = new FormData();
formData.append("name", "test")
formData.append("price", 150)
formData.append("brands", [1, 2])
let response = await axios.post("/createProduct", formData)
}
And then console.log() the typeof each property on the back-end, I always get a string:
console.log(typeof req.body.brands) --> String 1, 2
console.log(typeof req.body.price) --> String 150
Why is this happening and how can I turn them to their original data types? I guess I can turn the req.body.price to integer with parseInt(), but how to turn req.body.brands back to an array?
I'm assuming you're using something like multer as a body parser to handle form-data.
You are adding the array wrong. The formData.append() function only accepts a string as argument. This causes [1,2] to be converted to a string automatically which conveniently is equal to [1,2].join(', ').
However, form-data does indeed support multiple values which multer will parse into arrays. But note that it support multiple values. Not arrays. So the correct syntax to add an array of values is:
formData.append("brands", 1);
formData.append("brands", 2);
Or more generally:
[1,2].forEach(x => formData.append("brands", x));
Doing this your backend should correctly parse the values into an array:
console.log(typeof req.body.brands) --> Array [1,2]
Your question is very confusing. How do you console.log() on the back-end?
If you meant, front-end and you are using PHP or whatever, if you receive an object response, you still have to convert it to your desired data type.
For JSON
var a = JSON.parse(response)
Then if you're expecting an array,
you should make the response an array type in the server. That way, Javascript will automatically detect it as an array.
console.log(response.length)
If you want convert your data to array in the server:
$data = array(1,2,3);
Then ensure you use a proper encoding type to flush response back to the HTML page.
echo json_encode($data);
If you already have your data and want to convert it to an array, do this:
var arr = [];
var data = response.split(',');
//Loop through data
for(var x=0;x < data.length;x++) {
arr.push(data[x]);
}
console.log(typeof arr) //Array (Object)```
Ordinarily, The ```arr = arr.split(',');```
is already an array and can be worked on

Converting string to a valid JSON object

hey there i saw many questions about this topic but none of them fit my question.
i'm trying to use localStorage to store a user custom preferences, i try put an json object into a localStorage key and use it later on.
the object at the beginning looks like that:
Object {test: "{a:"b",c:"d"}"}
the JSON.parse method returns an error, what i done is that:
var local_storage = getAll();
$.parseJSON(JSON.stringify(local_storage.test.substring(0,0).substring(0,local_storage.length,-1)));
the output is :
{a:"b",c:"d"}
but i can't use it as local_storage.test.a why is that and what is the solution for that?
thx for the help :)
Edit!
Thanks to #Oli Soproni B, the solution is:
var key = {a:"b",c:"d"};
var l = JSON.stringify(key);
localStorage.setItem('test',l);
var local_storage = $.parseJSON(localStorage.getItem('test'));
console.log(local_storage);
console.log(local_storage.a);
// data
var k = {a:"b", c: "d"};
// stringify json
var l = JSON.stringify(k);
// set item to local storage
localStorage.setItem('test', l);
// get item to local storage and parse data
var local_storage = $.parseJSON(localStorage.getItem('test'));
console.log(local_storage);
Object {a: "b", c: "d"}
console.log(local_storage.a);
prints b
// or use
var local_storage = JSON.parse(localStorage.getItem('test'));
// in parsing the stringify json data
Localstorage stores string, not object. So you need to convert object to string while storing and converting it to object while retrieving.
To store:
localStorage.setItem("key",JSON.stringify(obj));
To retrieve:
obj = JSON.parse(localStorage.getItem(obj));
See DEMO here.
You used Json.stringify, because you need to store the data into localstorage as a string only.
you need to parse that again to JSON in order to use it as a JSON object,
but not like this
JSON.stringify(local_storage.test.substring(0,0).substring(0,local_storage.length,-1))
This tries to get a substring from your previously stored string, and again tries to stringify it.
You can get the stored string directly like this,
var local_storage = getAll();
var test=JSON.parse(local_storage.test);
And then use, as the test object, as test: {a:"b",c:"d"}

Convert Javascript string or array into JSON object

I have a JavaScript variable with comma separated string values - i.e. value1,value2,value3, ......,valueX,
I need to convert this variable's values into a JSON object. I will then use this object to match user enteredText value by using filterObj.hasOwnProperty(search)
Please help me to sort this out.
What you seem to want is to build, from your string, a JavaScript object that would act as a map so that you can efficiently test what values are inside.
You can do it like this :
var str = 'value1,value2,value3,valueX';
var map = {};
var tokens = str.split(',');
for (var i=tokens.length; i--;) map[tokens[i]]=true;
Then you can test if a value is present like this :
if (map[someWord]) {
// yes it's present
}
Why JSON? You can convert it into an array with split(",").
var csv = 'value1,value2,value3';
var array = csv.split(",");
console.log(array); // ["value1", "value2", "value3"]
Accessing it with array[i] should do the job.
for (var i = 0; i < array.length; i++) {
// do anything you want with array[i]
}
JSON is used for data interchanging. Unless you would like to communicate with other languages or pass some data along, there is no need for JSON when you are processing with JavaScript on a single page.
JavaScript has JSON.stringify() method to convert an object into JSON string and similarly JSON.parse() to convert it back. Read more about it
All about JSON : Why & How
Cheers!!
JSON format requires (single or multi-dimensional) list of key, value pairs. You cannot just convert a comma separated list in to JSON format. You need keys to assign.
Example,
[
{"key":"value1"},
{"key":"value2"},
{"key":"value3"},
...
{"key":"valueX"}
]
I think for your requirement, you can use Array.

How can I pass string or array to another page without querystring in javascript?

I have string variable and array in my page. I want to pass these variables to another pages. For string variable yes I can use querystring but for array what can I do?
localStorage can only handle strings which is why you have to first convert your array into a string before storing it.
var yourArray = [ 1, 2, 3 ];
// Store it
localStorage['foo'] = JSON.stringify( yourArray );
// And retrieve it
var storedArray = JSON.parse( localStorage['foo'] );
Like others have said the above only works with modern browsers so if you are worried about browser compatibility you can store your array in a cookie.
If you have concerns regarding size restrictions of cookies and the size of your array check out this question
You can store it in localStorage assuming the user has a modern browser. Otherwise you could serialize it, e.g. to JSON, and store it in a cookie.

Storing arrays in javascript for javascript

I've seen lots of articles on how to serialise arrays from javascript to send to PHP files which the PHP file will then deserialise back into an array, etc...
I have a large-ish nested associative array in my javascript which I need to save to a string and at a later date retrieve and convert back into a string in javascript. No other program will ever touch this. It may be handy if the serialised data is human-readable but it is absolutely not a requirement.
There is an intermediate PHP file but it's only 4 lines long: all it does is save the string to a file and send it back when requested. I'm not interested in parsing the array in PHP.
What is the fastest and simplest way to convert a multi-nested associative array in javascript to a string and back again?
JSON is a subset of the JavaScript language that is widely used as a serialization format, both for JavaScript and increasingly for other languages as well. It's human-readable, except that most implementations remove optional whitespace, which makes it a bit more difficult.
Modern browsers have JSON support out-of-the-box, for older ones you will need to include a library like json2.js.
To serialize, you use the JSON.stringify method.
var myObject = {a: 2, b: 3, c: [1, 2, 3]};
var serialized = JSON.stringify(myObject);
// serialized == "{"a":2,"b":3,"c":[1,2,3]}"
To unserialize, you use the JSON.parse method.
var recovered = JSON.parse(serialized);
Well, I have constructed my array like: var data = new Array(); data["John"] = "John Smith";
Ah, this is a problem. A JavaScript Array isn't meant to be used as an associative array, it's meant as a normal zero-indexed non-associative array. You can assign properties (key/value pairs) to any JavaScript object, which is why your code is working, but the fact thay your object is an Array is probably going to cause problems. If you just create a new Object() instead things should work better.
You'll want to serialize your array into JSON:
serialized = JSON.stringify(myobject)
To get it back
myobject = JSON.parse(serialized)
http://www.json.org/js.html
var someArray = [];
someArray.push({someObjectProperty: 'someValue' });
someArray.push({someObjectProperty: 'someValue2' });
console.log(someArray);
var stringVersion = JSON.stringify(someArray);//You can save the string version anywhere...
console.log(stringVersion);
var someNewArray = JSON.parse(stringVersion);
console.log(someNewArray);
Everyone has explained this well on the Javascript side, but this is how it happens on the PHP side:
<?php
$arr = Array(1, 2, 3, 'a', 'b', 'c'); // an array in PHP
echo json_encode($arr); // output the array as JSON: [1,2,3,'a','b','c']
?>
<?php
$json = "[1,2,3,'a','b','c']"; // a JSON string to be parsed by PHP
$arr = json_decode($json); // this is our original array in PHP again
?>

Categories