Storing key values array in localstorage - javascript

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.

Related

Fetch localstorage value in array

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.

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/

Get the length of an array within a JSON object

I want to find out how many items are in my JSON object. I have seen many answers but they all deal with a common value to loop through. I am wanting the results to tell me that there are 2 items in this object. Any help would be great!
[{"manager_first_name":"jim","manager_last_name":"gaffigan"}]
You could use Object.keys in newer browsers. It would return an array of all the keys in the object, and that array would have a length property that will tell you how many items there are in the object :
var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var length = Object.keys(arr[0]).length;
FIDDLE
In non-supporting browsers, you have to iterate
var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var i = 0;
for (var key in arr[0]) i++;
FIDDLE
You can do this:
var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}],
length = 0,
obj = arr[0]; // Get first obj from array
for(var k in obj){
if( obj.hasOwnProperty(k) ) {
length++;
}
}
console.log(length); // Shows 2
You should use hasOwnProperty because you can also extend an Object with functions, there could otherwise also be count als keys.
Links:
hasOwnProperty
Try
var jsonArr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var itemCount = JSON.stringify(jsonArr).split('":"').length - 1;
This is, of course, a rather coarse(and unreliable) way of doing it, but if you just want the item count, this should work like a charm.

Can't reference array by index

I have an array defined as:
var subjectCache = [];
I then have some code to build it up, which is working ok.
However, if I try to reference the array by an index, e.g.:
var x = subjectCache[0];
or
var x = subjectCache[1];
I get undefined.
Also subjectCache.length is always 0 (zero).
if I try to reference it by its key, e.g.:
var x = subjectCache['12345'];
it works.
Is this normal? Shouldn't I be able to reference it by its index whatever?
I'm using Internet Explorer, if it makes a difference (and it probably does :( )
[Edit]
this is the code I'm using to build the array, although I really don't think it is to blame.
It's a callback from a webservice call. This is working fine and the array is being populated.
var subjectCache = [];
var subjectCacheCount = 0;
function refreshSubjectsCallback(data) {
// update subjects
// loop through retrieved subjects and add to cache
for( i=0; i < data.length; i++ )
{
var subject = data[i];
var subjectid = subject.SubjectId;
subjectCache[subjectid] = subject;
subjectCacheCount += 1;
}
}
[/Edit]
You're probably assigning keys manually instead of using subjectCache.push() to add new elements to the array:
var array = [];
array['foo'] = 'bar';
console.log(array.length); // 0
The length attribute isn't going to reflect those changes the way you'd expect:
> var a = [];
undefined
> a[100] = 2; // The previous `100` entries evaluate to `undefined`
2
> a.length;
101
Instead, use an object:
var object = {};
object['foo'] = 'bar';
for (var key in object) {
var value = object[key];
console.log(value);
}
From your symptoms, it sounds like you are trying to treat the array as an associative array.
In Javascript, arrays work like this:
var a = [];
a[1] = 10;
alert(a.length);
Objects work like this:
var o = {};
o.myProp = true;
o["myOtherProp"] = false;
Arrays only work with numeric keys not strings. Strings assign properties to the object, and aren't counted as part of length nor it's numeric indices.
When building the array, make sure you are assigning to a numeric position within the array.
No, it will not work, because you haven't created arrays but objects.
you will have to access it by its key.
var x = subjectCache['12345'];
If this works and subjectCache.length doesn't, I think you are making an object not an array. You are confused.
Somewhere along the road you lost the array, and the variable subjectCache points to a different kind of object.
If it was an array, it can't have the length zero and contain an item that is reachable using subjectCache['12345']. When you access an item in an array it doesn't make any difference if you use a numeric index or a string representing a number.

JavaScript Variable Declaration

This is a really stupid question, but I'm just drawing a blank here...
What type of variable declaration is this:
var s1 = [1,2,3,4]
Also, How can I construct a variable like this from multiple objects when the amount of those objects is unknown. This is what I came up with, which doesn't work.
var s1 = [];
for(x in data[i].uh) {
s1 += data[i].uh[x];
}
var s1 = [1,2,3,4]
is an array declaration of four integers using "Array Literal Notation"
You don't need a loop to copy the array, simply do this:
var s1 = data.slice(0);
or in your example you might want this:
var s1 = data[i].uh.slice(0);
Read more about copying arrays here: http://my.opera.com/GreyWyvern/blog/show.dml/1725165
"The slice(0) method means, return a
slice of the array from element 0 to
the end. In other words, the entire
array. Voila, a copy of the array."
That is called an Array, which can be declared with new Array() or by using the array literal [] as in your example. You can use the Array.push() method (see docs) to add a new value to it:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
This
var s1 = [1,2,3,4]
is an array declaration.
To add an element to an array, use the push method:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
s1 is an array, it's a proper Javascript object with functions.
var s1 = [];
is the recommend way to create an array. As opposed to:
var s1 = new Array();
(see: http://www.hunlock.com/blogs/Mastering_Javascript_Arrays)
To add items to an array use s1.push(item) so your code would be:
var s1 = [];
for(x in data[i].uh) {
s1.push(data[i].uh[x]);
}
As a side note, I wouldn't recommend using for-in, at least not without checking hasOwnProperty.
It's declaring a local variable with an Array with 4 members.
If you want to append to an Array, use the push() method.
That is an array. To add to arrays you would use Array.push(). For example:
var s1 = [];
s1.push(1);
s1.push(2);

Categories

Resources