How to retrieve multiple keys and values from localStorage - javascript

I am storing multiple arrays to localstorage.
firstArray = [];
secArray = [];
var firsteobj = {class: class, subject: subject, school: school, area: area, zipcode: zipcode};
firstArray.push(firstobj);
localStorage.firstRecord = JSON.stringify(firstArray);
var secobj = {student: student, grade: grade, age: age};
secArray.push(secobj);
localStorage.secondRecord = JSON.stringify(secArray);
And I am retrieving from the localstorage through the function and download the file.
function DownloadRec() {
var a = {};
for (var i = 0; i < localStorage.length; i++) {
var k = localStorage.key(i);
var v = localStorage.getItem(k);
a[k] = v;
//alert(a[k]);
}
let dataUrl = 'data:application/json,' + encodeURIComponent(a[k]);
let exportFileDefaultName = 'test.json';
let linkElement = document.createElement('a');
linkElement.setAttribute('href', dataUrl);
linkElement.setAttribute('download', exportFileDefaultName);
linkElement.click();
}
I could see both key(firstRecord,secRocord) and corresponding values to it in the browser.
I could retrieve only the first key which is localstorage.firstRecord.... I would like to retrieve second key and values which is localstorage.secondRecord also.
Could you please suggest me.

Just create an array of objects like this:
arr=[
obj1:'',
.
.
.
obj2:''
]
and save it in browser using localStorage.setItem('objName') now you can retrieve the whole array.I think this is the best approach in your case.

The proper way to set/get localStorage is like this:
const myValue = [{ thing: 'myValue' }]
const mySerializedValue = JSON.stringify(myValue)
localStorage.setItem('myKey', mySerializedValue)
localStorage.getItem('myKey')
Also, I noticed "class" being used as a variable name. Might want to rename because "class" is a keyword in many programming languages, including es6 javascript.

You can store multiple values in localstorage using following. Also you can store data in the form of JSON objects as demonstrated:
//Store Values:
localStorage.setItem('someValue','hello');
let user = {name: 'SomeName', email: 'someemail#gmail.com'};
localStorage.setItem('jsonValue',JSON.stringify(user));
//Retrieve the values from localstorage
let temp = localStorage.getItem('someValue'); //temp is hello
let tempJSONString = localStorage.getItem('jsonValue');
let tempJSON = JSON.parse(tempJSONString );
//tempJSON.name is SomeName

Related

How to declare an object of arrays of custom type in typescript

I am searching how to declare a variable where I can store users by birthdate while avoiding using any
let formatedUsers = {} as "TYPE_NEEDED"
for (let i = 0; i < users.length; i++) {
const user= users[i];
if (!formatedUsers[user.birthdate]) formatedUsers[user.birthdate] = [];
formatedUsers[user.birthdate].push(user);
}
In the end I want my variable "formatedUsers" to be like this:
formatedUsers = {
12-02-1996: [user1, user3, user4],
02-04-1998: [user2],
05-08-1999: [user5, user6]
}
The object keys are strings, and the object values are arrays of users, so a relatively simple Record will do it. Assuming you have a reference to the type of user, you can do:
const formattedUsers: Record<string, User[]> = [];
If you don't have a reference to the user type, you can extract it first.
type User = (typeof users)[number];
In that case, you can use the Record interface.
let formatedUsers: Record<number, User[]> = {0:[]};
You can also initialize the value like that.
This is more accurate since it requires keys to be number-number-number
const formattedUsers: Record<`${number}-${number}-${number}`, User[]> = {};

Adding key to multiple values in an object

I am looking to grab a string value from a text box and multiple values from a multiselect list and associate them where the string value is the key, and the multiple values from the drop down list are the values.
Here is the javascript code I have thus far:
var serviceName = document.getElementById('servicePackageText').value;
var sourceType = document.getElementById("multiple-checkboxes");
var groupName = serviceGroupName;
var serviceArray = new Array();
for (i = 0; i < sourceType.selectedOptions.length; i++) {
serviceArray.push(parseInt(sourceType.selectedOptions[i].value));
}
I want the format to look like this:
"Textbox value": [
multiselect_values,
multiselect_values,
multiselect_values,
multiselect_values
]
Any tips on how to proceed?
You need wrapper object, then it is easy. All you have to do is use [] property accessor to assign the object property.
I took some liberty with your code to make it simpler to rationalize:
var serviceName = "myDog"; //mock document.getElementById('servicePackageText').value;
var sourceType = [1, 2, 3, 4]; //mock document.getElementById("multiple-checkboxes");
var groupName = {};
groupName[serviceName] = sourceType; // <--- THE ANSWER
console.log(groupName);

Create dynamic variable names and values using for loop: JavaScript

I have a list of values that I want to dynamically assign to another list of values:
var activeMachines = [41,44,46]
for(i = 0; i < activeMachines.length; i++){
var temp + activeMachines[i] = document.getElementById("tempData"+activeMachines[i]);
var humid + activeMachines[i] = document.getElementById("humidData"+activeMachines[i]);
var time + activeMachines[i] = document.getElementById("timeData"+activeMachines[i]);
}
What I am hoping to achieve is that this loop would create 6 new variables in total:
temp41 = document.getElementById("tempData41");
temp44 = document.getElementById("tempData44");
...
Above is not working. I have read some other posts suggesting using arrays, but I think I need to somehow dynamically create a dictionary, and I can't seem to get the syntax right to achieve this. any suggestions?
Anytime you're struggling to dynamically define variable names it's an indication that you should step back and reconsider your data structures. It's almost always the wrong choice that leads to difficult, messy code.
In this case it looks like you have three things that have an id and a temp, humidity and time property. This is exactly what objects are for.
For example you might represent the data like:
let data = { machine_41: {temp: 40, humid: 10, time: 200},
machine_44: {temp: 30, humid: 15, time: 500},
} // etc
Now all your data is in one place and you can access it with simple properties:
data.machine_41.temp
To go from your array of numbers to this object is simple with reduce():
var activeMachines = [41,44,46]
let data = activeMachines.reduce((obj, machineID) => {
// some fake data
temp = 20 // or document.getElementById etc..
humidity = 10
time = 600
obj['machine_'+machineID] = {temp, humidity, time}
return obj
}, {})
console.log("machine_41 humidity:",data.machine_41.humidity)
console.log(data)
This might not be the exact data structure you need (maybe it's better as an array for example), but this approach will serve you better than trying to create a bunch of individual variables.
You can use the window object for doing that, however, I recommend you to create your own object to store those "variables" as properties within that new key-value object.
var activeMachines = [41,44,46]
var obj = {};
for(i = 0; i < activeMachines.length; i++){
obj['temp' + activeMachines[i]] = document.getElementById("tempData"+activeMachines[i]);
obj['humid' + activeMachines[i]] = document.getElementById("humidData"+activeMachines[i]);
obj['time' + activeMachines[i]] = document.getElementById("timeData"+activeMachines[i]);
}
Try this
var activeMachines = [41,44,46];
var output = {};
for(i = 0; i < activeMachines.length; i++){
output["temp" + activeMachines[i]] = document.getElementById("tempData"+activeMachines[i]);
output["humid" + activeMachines[i]] = document.getElementById("humidData"+activeMachines[i]);
output["time" + activeMachines[i]] = document.getElementById("timeData"+activeMachines[i]);
}
console.log(output);
All your variables are define in this variable.
Access like output['temp41']
You can use an object and create properties instead of variables.
var context = {};
for (i = 0; i < activeMachines.length; i++) {
context[`temp${activeMachines[i]}`] = document.getElementById("tempData"+activeMachines[i]);
}
And the access those data with context.temp41 or context["temp41"]

Array with key value string into Object JavaScript

I am looking for some help, I am working on a piece of code for a client, the client currently have their analytics tag hardcoded to the page with all the key values being sent.
We are in the process of converting them to a new analytics platform using a tag management system, they have been able to update the majority of their platforms to create an object that the new analytics platform can reference but as this site is managed by a 3rd party they are unable to get this resolved in time for our release.
I have managed to successfully pull the tag and split the tag in to parameters:
var x = $('img[alt="MI_TAG"]').attr("src");
x.split("&");
Which creates the array:
1:"109=jsp.searchFlights.initial"
2:"117=Flight Only Journey"
3:"206=02/11/2017"
4:"208=03/11/2017"
5:"212=ALL"
What I want to do is take these array strings to create an object call "mi", like so:
109:"jsp.searchFlights.initial"
117:"Flight Only Journey"
204:""
205:""
206:"02/11/2017"
208:"03/11/2017"
Can someone help?
Thanks all for your help, I have managed to take some of the advice here and create the object and see it logging out:
var x = $('img[alt="MI_TAG"]').attr("src");
var split = x.split("&");
var arrayLength = split.length;
var arr = [];
var i = 0;
do {
arr.push(split[i].replace('=',':'));
arr.toString();
console.log(arr);
i += 1;
} while (i < arrayLength);
let mi = {};
arr.forEach(item=>{
let tempArr = item.split(':');
mi[tempArr[0]] = tempArr[1];
})
console.log(mi);
The issue I now seem to be facing is scope, I want my object to be globally referenceable, how do I do that?
From your array, use reduce - split on the = sign in your string, and create the object:
let newObject = arr.reduce((obj, item) => {
let parts = item.split("=");
obj[parts[0]] = parts[1];
return obj;
}, {});
Assuming you are using at least ECMAScript 5.1 you could use Array.prototype.forEach() to iterate over your array and produce the object.
let myArray = ["109=jsp.searchFlights.initial", "117=Flight Only Journey", "206=02/11/2017", "208=03/11/2017",
"212=ALL"];
let myObject = {};
myArray.forEach(item=>{
let tempArr = item.split('=');
myObject[tempArr[0]] = tempArr[1];
})
console.log(myObject);
Produces:
{
"109": "jsp.searchFlights.initial",
"117": "Flight Only Journey",
"206": "02/11/2017",
"208": "03/11/2017",
"212": "ALL"
}

Javascript multidimensional array not working

How to create multidimensional array??
I tried it so far:
var post_data = [];
var id = 1;
post_data[id] = [];
post_data[id]['name'] = 'abc';
post_data[id]['date'] = '01-03-2014';
post_data[id]['country'] = 'India';
console.log(post_data);
the above code is not giving me the key. Whats wrong?
DEMO FIDDLE
i want a output something like this:
[1]=> array
(
"name": "abc",
"date": "01-03-2014",
"country": "India",
)
How to get the above output???
To get wished result you can change
var post_data = [];
to
var post_data = {};
and
post_data[id] = {};
You are trying to make an array of object.
Try this : -
post_data[id] = {};
You are using the inner array as an object. The properties that you set on the array still is there, when you display it only the array items are shown.
You should use an object instead of an array, as you are not using the array as an array:
post_data[id] = {};
Instead of setting the properties after creating the object, you can set them when you create it:
post_data[id] = {
name: 'abc',
date: '01-03-2014',
country: 'India'
};
In the third line of code you have to write
post_data[id] = new Array();
So the entire code section looks like
var post_data = [];
var id = 1;
post_data[id] = new Array();
post_data[id]['name'] = 'abc';
post_data[id]['date'] = '01-03-2014';
post_data[id]['country'] = 'India';
console.log(post_data[id]['name']);
This should fix it, best of luck :)

Categories