I add an array localstorage. works fine. I can also retrieve it . how can I.update where ID is something without adding a new array.
example ..
how can I go update surname and age where ID = sam without creating new array
var objItem = {};
if (localstorage.getItem("records") == null) {
objArr = [];
} else {
objArr = JSON.parse(localstorage.getItem("records"));
}
var ID = "sam";
var surname = "edward";
var age = "two";
objItem.ID = ID;
objItem.surname = surname;
objItem.age = age;
objArr.push(objItem);
localstorage.setItem("records", JSON.stringify(objArr));
localStorage is just a key-value store. To update, you just save to the same key. That is, you retrieve your array, parse, update, stringify then save to the same key.
To find the item on the array, you can use array.filter and create an array containing only the values that match the ID. Update the values inside that array and save the original array.
let names = [...names...];
let matches = names.filter(person => person.ID === ID);
matches.forEach(person => person.surname = surname);
let toSave = JSON.stringify(names);
// save to localstorage
Related
I am trying to save input values submitted through form into local storage in the form of the array, but once the form is submitted again, the saved value in local storage gets changed with the new submitted value as the
function bookDetails(bookName,bookAuthor,bookType) {
this.name = bookName;
this.author = bookAuthor;
this.type = bookType;
}
let libraryForm = document.getElementById("bookForm");
libraryForm.addEventListener("submit", libraryBooksDetails);
function libraryBooksDetails(e,index) {
e.preventDefault();
console.log("The book details have been submitted");
let bookName = document.getElementById("bookName").value;
let bookAuthor = document.getElementById("author").value;
let bookType;
let fiction = document.getElementById("Fiction");
let programming = document.getElementById("ComputerProgramming");
let personal = document.getElementById("PersonalDevelopement");
if(fiction.checked){
bookType = fiction.value;
}
else if(programming.checked){
bookType = programming.value;
}
else if(personal.checked){
bookType = personal.value;
}
// BookDetails Object
let book = new bookDetails(bookName,bookAuthor,bookType);
let bookData = ""
bookData = bookData || [];
let nameOfBooks = bookData.concat(bookName)
// let nameOfBooks = bookData
// nameOfBooks.push(book.bookName);
localStore.setItem("books",JSON.stringify(nameOfBooks))
console.log(book);
let display = new Display()
display.add(book);
display.clear();
}
Thanks
I'm not sure I understand the question completely because you are setting the value let book = new bookDetails but that is not what you are storing in local storage.
// First time bookData value is set, this is always an empty string
let bookData = "";
// Since empty string is a falsey value, bookData value is re-set to an empty array
bookData = bookData || [];
// nameOfBooks is initialised as an array with one value of bookName
let nameOfBooks = bookData.concat(bookName);
// books key in local storage is a stringified array with one item
localStore.setItem("books", JSON.stringify(nameOfBooks));
localStorage.setItem(key, value) will always replace the existing value at that key. If you want to append to the stored value, first get the value and parse it before appending the new value.
const oldValue = localStorage.getItem('books');
const parsed = JSON.parse(oldValue);
const newValue = parsed.concat(nameOfBooks);
localStorage.setItem('books', JSON.stringify(newValue));
so basically i want to make a phone contacts app, and i try to save the saved contact to local storage
so this is the function when the save button clicked
saveContact(name, number){
//To check if the name input or phone input is not blank
if(nameInput.value == '' || phoneInput.value == ''){
info.style.display = 'block'
}
const firstLetter = name[0].toUpperCase()
const getContact = localStorage.getItem(firstLetter)
const storedObject = {
[name]:number
}
//If contact's first letter exists in localstorage
if (getContact){
const oldData = [JSON.parse(localStorage.getItem(firstLetter))]
oldData.push([storedObject])
const oldDataString = JSON.stringify(oldData)
localStorage.setItem(firstLetter, oldDataString)
const finalOldData = []
//i do a looping here to push each contact's object to a new array which is finalOldData
//but it doesn't work well. it doesn't actually add a new object to the array instead of replacing the old object with a new one
oldData.forEach(e => {
finalOldData.push(e[0])
})
const finalOldDataString = JSON.stringify(finalOldData)
localStorage.setItem(firstLetter, finalOldDataString)
}
//If contact's first letter doesn't exist in localstorage
else{
const storedObjectString = JSON.stringify([storedObject])
localStorage.setItem(firstLetter, storedObjectString)
this.clearSave()
}
}
so the issue is when i try to add a contact which its first letter exist in local storage and make it as a list
//and this is the result i want
Storage
A: "[{\"amber\":\"1242134\"},{\"annie\":\"123421\"}]"
length: 1
You can consider the code below, it is working as expected.
Changes
const oldData = [JSON.parse(localStorage.getItem(firstLetter))]
No need to put the result from JSON.parse into an array, it already is an array and also you can use the variable getContact instead of calling getItem again on localStorage.
oldData.push([storedObject])
No need to push an array into oldData, simply push storedObject.
I've removed the initial check for making testing easy, you can add it back.
function saveContact(name, number) {
if (!name || !number) {
return;
}
const firstLetter = name[0].toUpperCase();
const getContact = localStorage.getItem(firstLetter);
const storedObject = { [name]: number };
if (getContact) {
const oldData = JSON.parse(getContact);
oldData.push(storedObject);
const oldDataString = JSON.stringify(oldData);
localStorage.setItem(firstLetter, oldDataString);
} else {
const storedObjectString = JSON.stringify([storedObject]);
localStorage.setItem(firstLetter, storedObjectString);
}
}
I am trying to save my variables in an array. Theses variables are written in by the user and saved to localStorage when a button is pressed. On my other html page i reach these variables and put them in 3 different arrays(the variables, that go in three arrays). Then the user writes in new text and save to the variables. Now to the problem. The newly created variables don't add to the array, they replace. I'm thinking this is due to to the same variable name however I can't find an solution.
I have tried to change variable names etc for saving the new variable but cant find solution.
//This is html page 2 (gets the items from localhost)
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar");
var TankaLiterVar= localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
var arrayKostnad = [];
var arrayLiter = [];
var arrayDatum = [];
arrayKostnad.push(TankaKostnadVar,);
arrayLiter.push(TankaLiterVar,);
arrayDatum.push(TankaDatumVar,);
document.write(arrayLiter,arrayKostnad,arrayDatum); //Ignore this, just test
//This is the code where the user is writing and it saves to localStorage.
//Html page 1 that saves the variables
var TankaKostnadVar = document.getElementById("tankaKostnad").value;
var TankaLiterVar = document.getElementById("tankaLiter").value;
var TankaDatumVar = document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", TankaKostnadVar);
localStorage.setItem("StorageLiterVar", TankaLiterVar);
localStorage.setItem("StorageDatumVar", TankaDatumVar);
I expect the array to add the variable. So if the user writes an 5 the array should first be [5] then when the user writes an 8 the array should be [5,8]
If you don't want use JSON, you can save string comma separated and, when necessary, transform the items to numbers. To transform in numbers you can use map function or a for. Localstorage only save strings, so if you need to be back to numbers you need to use JSON.parse or use function parseInt, that is global.
//Retrieve saved items from localstorage
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar"); // "1,2"
var TankaLiterVar = localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
TankaKostnadVar += "," + document.getElementById("tankaKostnad").value;
TankaLiterVar += "," + document.getElementById("tankaLiter").value;
TankaDatumVar += "," + document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", TankaKostnadVar);
localStorage.setItem("StorageLiterVar", TankaLiterVar);
localStorage.setItem("StorageDatumVar", TankaDatumVar);
// if you want to transform TankaKostnadVar and others two, just do like this
TankaKostnadVar.split(','); // result: ['1', '2']
// if you want to transform to number
TankaKostnadVar = TankaKostnadVar.split(',').map( function(number) {
return parseInt(number)
} );
The split function of string, breaks a strings in parts separated by one string. In this case, breaks a string separated with comma. So "1,2" turns into ['1', '2'].
If you want to keep adding to the array you'll need to push the entire array you're holding in memory up to localStorage after appending a new element. Alos, localStorage only stores string values so if you want to maintain the Array structure you'll have to use JSON.stringify() before running setItem() and then JSON.parse() next time you access those values with getItem().
//This is the code where the user is writing and it saves to localStorage.
//Html page 1 that saves the variables
var TankaKostnadVar = document.getElementById("tankaKostnad").value;
var TankaLiterVar = document.getElementById("tankaLiter").value;
var TankaDatumVar = document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", JSON.stringify( [TankaKostnadVar] ));
localStorage.setItem("StorageLiterVar", JSON.stringify( [TankaLiterVar] ));
localStorage.setItem("StorageDatumVar", JSON.stringify( [TankaDatumVar] ));
//This is html page 2 (gets the items from localhost)
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar");
var TankaLiterVar = localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
var arrayKostnad = JSON.parse(TankaKostnadVar);
var arrayLiter = JSON.parse(TankaLiterVar);
var arrayDatum = JSON.parse(TankaDatumVar);
// Now you have arrays with data, but I don't know what you want to do with them...
// you could add more values like this (still page 2)...
arrayKostnad.push('new value 1')
arrayLiter.push('new value 2')
arrayDatum.push('new value 3')
localStorage.setItem("StorageKostnadVar", JSON.stringify( arrayKostnad ));
localStorage.setItem("StorageLiterVar", JSON.stringify( arrayLiter ));
localStorage.setItem("StorageDatumVar", JSON.stringify( arrayDatum ));
// now check the values again
var TankaKostnadArr = JSON.parse(localStorage.getItem("StorageKostnadVar"));
var TankaLiterArr = JSON.parse(localStorage.getItem("StorageLiterVar"));
var TankaDatumArr = JSON.parse(localStorage.getItem("StorageDatumVar"));
document.write(TankaKostnadArr, TankaLiterArr, TankaDatumArr)
And this is what I would do to clean things up a little...
// Import these functions and variables to any file that needs to interact with LocalStorage
var storageKeys = ["StorageKostnadVar","StorageLiterVar","StorageDatumVar"];
function addToArray(key, val, arrObj) {
arrObj[key].push(val)
}
function storeAllLocalStorage(arrayObject) {
Object.keys(arrayObject).forEach(key=>{
localStorage.setItem(key, JSON.stringify(arrayObject[key]));
})
}
// Use above functions when needed
var storedArrays = storageKeys.reduce((acc,key)=> {
var val = JSON.parse(localStorage.getItem(key));
if (typeof val === 'array') return {...acc, [key]:val};
return {...acc, [key]:[val]};
},{})
addToArray("StorageKostnadVar", document.getElementById("tankaKostnad").value, storedArrays);
addToArray("StorageLiterVar", document.getElementById("tankaLiter").value, storedArrays);
addToArray("StorageDatumVar", document.getElementById("tankaDatum").value, storedArrays);
storeAllLocalStorage(storedArrays)
You are simply using localStorage.setItem which saves your values with the given key. If the key exists, it will replace the value. Before you do a .setItem, get the value from the local storage first, then parse it to array so that you can finally push the new user inputs to that parsed array. Then you can .setItem to replace the "outdated" value from the localStorage.
UPDATE Example:
Sorry for leaving this hangin without an example. Here it is:
// Get array from local storage
const stringifiedArray = localStorage.getItem('myCollection');
// If there is no 'myCollection' from localStorage, make an empty array
const myCollection = stringifiedArray ? JSON.Parse(stringifiedArray) : [];
myCollection.push('My new item added'); // update array
localStorage.setItem('myCollection', JSON.stringify(myCollection)); // save
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
$.cookie("matrizTela", null);
objCookie = {};
for(var i = 1; i<vList.length;i++){
for(var z=0;z<vList[i].length;z++){
listaY = vList[i][z].childNodes[0].attributes;
listaX = vList[i][z].style;
$.each(listaY,function(key,val){
objCookie[val.nodeName] = val.nodeValue;
});
$.each(listaX,function(key,val){
metodo = "listaX."+val;
propValue = eval(metodo);
objCookie[val] = propValue;
});
console.log(objCookie);
//Need now add objCookie in my cookie in list form!
}
};
OBS: vList is matrix of lists of the DOM Object
How can I dynamically add my objCookie in list form on my cookie?
Example:
$.cookie("matrizTela", ["objCookie", "objCookie","objCookie"]);
A cookie can store only String values.
The best you can do to store an array of objects is to serialize the array and store it as a string.
$.cookie("matrizTela", JSON.stringify(yourObjectArray));
For reading it back, you can do:
yourObjectArray = JSON.parse($.cookie("matrizTela"));