Fetch localstorage value in array - javascript

I am saving value in localstorage as shown below
key = profskill , value = "a,b,c"
In my test.ts file, I have declared array but I am unable to fetch the result in it. Code shown below:
getskills: Array<string> = [];
this.getskills = localStorage.getItem("profskill");
but this is giving error:
Type 'string' is not assignable to type 'string[]'
I want to fetch value like this:
console.log(this.getskills[0]);

The LocalStorage can only store strings, not objects or arrays. If you try to store an array, it will automatically be converted to a string. You need to parse it back to an array :
JSON.parse( localStorage.getItem("profskill") )

Since, you want the comma separated value to be represented as a array of strings for this.getskills use split on the value of the localStorage
Here is a sample example
//say we get the value 'a,b,c' from localStorage into the temp variable
//var temp = localStorage.getItem(profskill);
var temp= 'a,b,c';
this.getskills = temp.split(',');
console.log(this.getskills[0]);

localStorage only supports strings. Use JSON.stringify() to set the data in storage and JSON.parse() to get the data from storage and then use split(",") to split the comma separated data.
var obj = "a,b,c";
localStorage.setItem("profskill", JSON.stringify(obj));
var getskills = [];
getskills = JSON.parse(localStorage.getItem("profskill")).split(",");
console.log(getskills[0]);

First get the data from the LocalStorage:
var DataTableValue = JSON.parse(localStorage.getItem('dataTableValue'));
Then, store in an Array:
var tempArray = new Array();
for (var i = 0; i < DTarray.length; i++) {
tempArray.push(DTarray[i]);
}
All data will be stored in the variable tempArray.

Related

How do I update my array with my object's value? [duplicate]

This question already has answers here:
How do I update specific key value of the local storage array?
(4 answers)
How to store and update a localStorage key object which has properties of different data types?
(1 answer)
Closed 4 years ago.
myObj is storing the input coming from the user which is pushed to arr which is store in localStorage as a 'data' key. On submit, I want the new values to be added to arr and not overwrite it (in the else part). The following code works but overwrites the old data:
var myObj = {
field1: fname.value,
field2: lname.value,
field3: birth.value,
field4: salary.value,
field5: String(selectedGender),
field6: String(choicesOfHobby),
field7: color.value,
field8: String(choicesCountry),
field9: textArea.value
}
const arr = new Array()
if (window.localStorage.length == 0) {
const arr = JSON.stringify(myObj);
window.localStorage.setItem('data', arr);
} else {
const arr = JSON.stringify(myObj);
window.localStorage.setItem('data', arr);
}
One thing to note is that JSON.stringify returns a string, not an array -- and, conveniently, localStorage stores key/value pairs where the value is a string, so this all works as it's supposed to.
To update the value in localStorage, you could first retrieve it, then modify it however you like, and then store it again. Since you're working with javascript objects, you'll need to use JSON.parse and JSON.stringify to convert back and forth between objects (to work with) and strings (to store).
This pattern looks like:
let retrievedString = localStorage.getItem('data');
let retrievedObject = JSON.parse(retrievedString); // convert string to obj
let oldColor = retrievedObject.field7; // we don't actually use oldColor
let newColor = "#666666";
retrievedObject.field7 = newColor; //change existing property
retrievedObject.field99 = "99"; // add new property
let modifiedString = JSON.stringify(retrievedObject); // ready to store new version
localStorage.setItem('data', modifiedString);
I added more to the code sample to clarify the kinds of things you can do with your retrieved object before converting back to a string and finally replacing the old version in storage.
Your mistakes:
arr, despite its name, isn't an array.
you never recover the saved data
Check the code below to see my take on the problem: (before trying it, you should erase your localStorage)
var myObj = {
field1: fname.value,
field2: lname.value,
field3: birth.value,
field4: salary.value,
field5: String(selectedGender),
field6: String(choicesOfHobby),
field7: color.value,
field8: String(choicesCountry),
field9: textArea.value
}
const array = window.localStorage.data || []; // get your saved array, or create a new one
array.push(myObj); // Add the current item to the array
window.localStorage.setItem('data', JSON.stringify(array)); // save it again
Any further question please just ask
You need to use something like this:
let data = localStorage.getItem('data');
let dataObj = JSON.parse(data);
dataObj[fieldKey] = fieldObj;
localStorage.setItem('data', JSON.stringify(dataObj));
Firstly read localstorage documents how to use it: https://developer.mozilla.org/tr/docs/Web/API/Window/localStorage
You have to push data array to localstorage and push your objects to your data array after getting data array from localstorage. Finally don't forget to set your data array to localstorage again. Your localstorage part code should be like below:
var data = JSON.parse(window.localStorage.getItem("data"));
if(data === null){
data = [];
}
data.push(myObj);
window.localStorage.setItem("data",JSON.stringfy(data));
You just need to use this:
arrInStorage = localStorage.getItem('data') || [];
arr = JSON.parse(arrInStorage);
arr.push(myObj);
localStorage.setItem('data', JSON.stringify(arr));
instead of your if / else statement.

convert json values in comma separated string using javascript

I am calling a third party web api, which returns data like this:
{"name":"Marine Lines","name":"jerry"}
I would like to convert this to a Json array, I could do a split by comma first and then by ":". but wondering if there are some better ways?
If the Web API return an object, then you can directly use dot-notation to access the value.
var x = {"name":"Marine Lines","name":"jerry"};
var name = x.name;
console.log(name);
Else if it is a string then you can parse it first using JSON.parse() and then do the same thing.
var x = '{"name":"Marine Lines","name":"jerry"}';
x = JSON.parse(x);
var name = x.name;
console.log(name);
First of all, your object has the name key twice, which means only the latter will be saved. As regards saving your object's values in an array, the following will do:
var
object = {"a": "Marine Lines", "b": "jerry"},
array = [];
/* Iterate over every enumerable property of the object. */
for (var key in object) {
/* Insert the value in the array. */
array[array.length] = object[key];
}
/* Log the created array. */
console.log(array);

JavaScript. How can I parse a string of vars and turn it into an object with properties

I am trying to parse a string in JS with a series of vars inline. The goal is to turn those vars into an object with name value pairs.
Example:
var hwStr = "color=blue+coreCnt=4+shell=aluminum+wireless=false";
I know I can parse the original string to get an array of name value pairs like this:
varArr = hwStr.split("+");
When I print that array I would get:
>color=blue,
>coreCnt=4,
>shell=aluminum,
>wireless=false
In order to create this object manually it would look like:
var hwSpec = {color: 'blue', coreCnt: 4, shell: 'aluminum', wireless: false};
My question is, how can I use a foreach statement to create an object that would have these as name value pairs.
To be fair JS is not my language, but I know that I SHOULD know this... This is probably a noob Question, any help would be great.
Gary C aka the UnKulMunki
After splitting on the plus signs, you can .reduce() the resulting array to process each key=value pair and add to an object:
var hwStr = "color=blue+coreCnt=4+shell=aluminum+wireless=false";
var obj = hwStr.split("+").reduce(function(o, item) {
item = item.split("=");
o[item[0]] = item[1];
return o;
}, {});
console.log(obj);
This is similar to using .forEach(), except instead of creating an empty object in a variable before calling .forEach() the empty object is passed as an argument to .reduce(). For this particular problem it doesn't make much difference, but in some cases .reduce() saves you having to create a temporary working variable.
EDIT: Note that my code creates all property values as strings - I don't think there's any way to know whether false should be treated as the boolean false or the string "false", unless you want to assume that all values that can be parsed as boolean or number should be treated as boolean or number.
First, you split the string at the + so you get an array of key/value pairs.
Then, you loop through those pairs and split each pair at the = to separate the key from the value. Then you assign the key as a property name and the value as the property value.
var hwStr = "color=blue+coreCnt=4+shell=aluminum+wireless=false";
// Split the string into an array of key/value pairs
var pairs = hwStr.split("+");
// Set up a new, empty object
var newObj = {};
// Loop through the key/value pairs array. The .forEach method takes
// a function as an argument that, itself, receives a value representing
// the current array item being iterated (a single key/value pair from
// the array in this case).
pairs.forEach(function(pair){
// Create a new property on the object with the key of the current pair
// and a value of the value of the current pair.
newObj[pair.split("=")[0]] = pair.split("=")[1];
});
console.log(newObj);
To do this, you have to use JSON's parse method to turn the string to javaScript object literal, this is how to do it:
var arr = hwStr.split("+");
var temp_arr = null;
var hwSpec = null;
var stringToConv = '{'; //string to convert to object literal
//iterate through the array
for (var i = 0; i < arr.length; i++){
temp_arr = arr[i].split("=");
stringToConv += '"' + temp_arr[0] + '":"' + temp_arr[1] + '"';
//check if is the last string in the arr
if (i === arr.length - 1){
stringToConv += '}'
}
else { //add comma
stringToConv += ",";
}
}
//convert to object using JSON
hwSpec = JSON.parse(stringToConv);
//your code here

Storing key values array in localstorage

I am trying to store array in localstorage with following code :
var tempval = [];
tempval['key'] = 1;
localStorage.setItem("Message", JSON.stringify(tempval));
but in localstorage it showing only []
So how to store it and where I am doing mistake ?
Here is your code:-
var tempval ={};
tempval.key = 1;
localStorage.setItem("Message", JSON.stringify(tempval));
So Your Question is not that much clear to me but i am trying to give you a general solution for storing multidimensional array in local storage ,
var a= [[1,2,3],["hello","world"]]; // multi dimentional array
console.log(a);
var b = JSON.stringify(a); // converting the array into a string
console.log(b);
localStorage.setItem("TestData",b); // storing the string in localstorage
var c= JSON.parse(localStorage.getItem("TestData")); //accessing the data from localstorgae.
console.log(c);
Here is the code running in Jsbin
JavaScript does not support arrays with named indexes.Arrays always use numbered indexes in javascript. Use object if you wanna use named index.
Using array (numbered index)
var tempval = [];
tempval[0] = 1;
Using object (named index)
var tempval = {};
tempval['key'] = 1;
Use var tempval ={}; instead of var tempval = [];
This question has been answer already (duplicate of):
https://stackoverflow.com/a/3357615/10387837
The short answer is localStorage.setItem only supports strings as arguments. In order to use it with arrays its recommended to use JSON.stringify() to pass the parameter and JSON.parse() to get the array.

Why an object key's first value is treated as a string - AngularJs

I have an object named as "param" and it has a key named as "item[]". The values of item[] are inserted dynamically.
Problem is when "item[]" has a single value, it treats that value as a string and not as first index of array.
Example :
item[]="123";
but when it has multiple values then it treats itself as an array which is desired, example-
item[] = ["123","456"];
I want the single value also as index of this array like
item[] = ["123"]
How would I do it ?
P.S. - This object is created from querystring parameters like http://example.com/def?item[]=123&item[]=456, then when I extract querystring, it returns these parameters as the keys of an object
I am extracting querystring in this way(Javascript)-
var param = $location.search();
console.log('Param');
console.log(param);//Returns Object{item[]=[2]} in console
This is because variableName[] is not a javascript syntax.
Since it does not recognise the [], it is probably part of the name if it does not throw an error.
To create an array, you have 2 possibilities :
//Contsructor
var ar = new Array(); //empty array
//Literal
var ar = []; //same as above
var ar = [0,1,2,3]; //array of length 4
var ar = new Array(4); //empty array of length 4
to access or set it
var ar[0] = "value"
Try this
queryString = ["123"];
queryString = ["123","432","456"];
if(queryString.length==1){
item.push(queryString[0]);
}else{
angular.forEach(queryString,function(value,key){
item.push(value);//push only value
})
}
I have solved it -
if(typeof param['item[]'] == "string"){
param['item[]'] = [param['item[]']];
}
First I am checking if the key has a string value, if it is string then I am converting it into an array and it worked.
Here is the working fiddle -
https://jsfiddle.net/r3vrxzup/

Categories

Resources