I have an object that I want to assign to the local storage , I mean can you loop over it ? any idea how to implement this ? The end result is the keys in the object must be keys as well in the local storage after using the setitem, I sure know how set and get singular items but in other words I want to mount and object on an empty local storage object.
const data = JSON.parse(object); // a prev localstroage object
console.log(data);
localStorage.setItem(...Object.keys(data), ...Object.values(data));
You have to use JSON.stringify(data); in order to store object in local storage.
Make sure you create your complete object in JavaScript itself (as per your requirement). And then once your object is ready, use JSON.stringify method to save objects in your local storage.
And to retreive back the data you will use JSON.parse() to get back the Object and then you can use any JavaScript methods to perform your tasks as per the requirement.
//To set
const obj = {
key: "Hello World"
}
const strObj = JSON.stringify(obj);
localStorage.setItem('strObj', strObj);
//To get
const strObjFromStorage = localStorage.getItem('strObj')
const objFromStorage = JSON.parse(strObjFromStorage)
console.log(objFromStorage);
You should be able to do so with JSON.stringify and JSON.parse :
// save object to localStorage
const myobj = {
x: 1,
y: 6
};
localStorage.setItem('key', JSON.stringify(myobj));
// fetch date as object from localStorage
let data = JSON.parse(localStorate.getItem('key'));