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"}
Related
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
I have a localstorage which is storing some data. I am trying to get the data in a component using localStorage.getItem('id'); but it is undefined. The problem is, localStorage is storing id in a strange format. It is stored like abcabcabc.id Now there are multiple such parameters in localStorage and for each logged in user the string abcabcabc changes. How can I still get id value. Can I compare string or something to get values? Like if it contains string .id only read that value? If yes, can you explain how would that be achieved?
localstorage:
abcabcabc.username.id = sdfsdfsdfs
abcabcabc.username.refreshToken = sdfsdfs
abcabcabc.username.accessToken = ertsdffdg
Since you do not know the exact key stored in localStorage fetch all of them and then iterate over it. Next, match part of the key that you know i.e id as illustrated below:
// fetch all key-value pairs from local storage
const localStorageKeys = { ...localStorage };
// iterate over them
for (const index in localStorageKeys) {
// see if key contains id
if (index.includes('id')) {
// fetch value for corresponding key
console.log(localStorageKeys[index]);
}
}
localStorage sets data as a map of key-value pairs, so :
var id = {key:"id", value:"sdfsdfsdfs"}
//JSON.stringify converts the JavaScript object id into a string
localStorage.setItem('id', JSON.stringify(id));
now you get the data by:
var getTheId = localStorage.getItem('id');
//you can use JSON.parse() if you need to print it
console.log('getTheId: ', JSON.parse(getTheId));
This is how you would normally do it, but since I don't know how you had set the data, you would instead get the data by:
var x = localStorage.getItem(id);//normally getting your id
//parse it
var st = JSON.parse(x);
var ids = [];
while(st.includes(id)){
//this is to only get the abcabacabc
var newId = st.substring(0,9);
ids.push(newId);
}
console.log(ids);
I know it is best way to use JSON but it is too complex for me to understand. Thus, may i ask is there any other ways to make sure that my data does not overwrite in local storage. Example using for loop or using another key name. Please help me by giving my examples as i am very new to HTML/JavaScript.
function saveToLS(){
var Name = document.getElementById("rName");
var namesaved = Name.value;
localStorage.setItem("Name",namesaved);
var Comment = document.getElementById("rComment");
var commentsaved = Comment.value;
localStorage.setItem("Comment",commentsaved);
}
Are you going to store multiples of these? You should store them in an array or object (for example adding a timestamp id field) and store that array in LS.
Yeah..Me Also new In this Part... but I hope to you help full this code please try It..
var key = 0;
for(key;key<10;key++){
localStorage.setItem(key, localStorage.getItem(key) + "Datas");
}
The best option is using JSON. JSON is not very complex. It's just a string which is a result of stringification of a language construct like an array or object.
What you need is an array: [], stringified version of it: "[]". So you need to push an element into the array. How? Convert the stored JSON string into an array by parsing it, and then push an element and stringify the new array. Here is an example:
var names = localStorage.getItem("Name");
names = names ? JSON.parse(names) : [];
names.push('newName');
localStorage.setItem("Name", JSON.stringify(names));
Also don't use 2 keys for storing 2 datum that belongs to one item. It will be hard to maintain. Use an object, an array of objects:
comments.push({
author: 'name of the author',
comment: 'here goes the comment body...'
})
function saveToLS(){
var Name = document.getElementById("rName");
var namesaved = Name.value;
if(localStorage.setItem("Name").length){ //the data already exists
// Do whatever if the data already Exists......
}else{
localStorage.setItem("Name",namesaved);
}
var Comment = document.getElementById("rComment");
var commentsaved = Comment.value;
if(localStorage.setItem("Comment").length){ //the data already exists
// Do whatever if the data already Exists......
}else{
localStorage.setItem("Comment",commentsaved);
}
}
check using localStorage.getItem(), if the data already exists and if its true don't write the data again or for that matter do whatever you want like save the data with another key
if(localStorage.setItem("Name").length){ //the data already exists
localStorage.setItem("SomethingElse...",namesaved); //something else
}else{
localStorage.setItem("Name",namesaved);
}
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.
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.