Access nested object values from local storage - javascript

How to get nested object values from localstorage.
For example:
"metadata":"{
"receiver":{"name":"John"},
"document":{"type":"Sample doc"},
"issuer":{"signatory":"Admin2"}}",
"options": "{"title\":"Document Title","expireOn":"2022-03-12T00:00:00.000Z"}"
I need to store and get values of name:john, type:sample, signatory:Admin.
localStorage.setItem('metadata', JSON.stringify(data.metadata));
let metadata = localStorage.getItem('metadata');
console.log('metadata: ', JSON.parse(metadata));
Thank you.

At first you should get the localStorage values and convert that to a JavaScript Object.
let metadata = JSON.parse(localStorage.getItem('metadata'))
Then you can easily get or store data.
// Store
metadata.receiver.name = 'example'
// Get
let name = metadata.receiver.name
You can do this way for other values also.

Have tried to save and get your JSON in localstorage.
Steps for getting nested object value.
Step 1: Sample JSON
var data = {"metadata":{"receiver":{"name":"John"},"document":{"type":"Sampledoc"},"issuer":{"signatory":"Admin2"}},"options":{"title":"DocumentTitle","expireOn":"2022-03-12T00:00: 00.000Z"}};
Step 2: Converting JSON Object to a String format and Save in
Localstorage window.localStorage.setItem("metadata", JSON.stringify(data.metadata));
Step 3: Fetch Stringify JSON from localstorage and parse var metadata = JSON.parse(window.localStorage.getItem("metadata"));
Step 4: Fetch nested Object value console.log(metadata.receiver.name)
Hope this answer is useful.

Related

How to save multiple form values as a consolidated String in Local Storage and retrieve them to be displayed on the browser

I'm trying to create a 'Notes' application which is basically a form that the user uses to enter 2 values, a name and a note.
I am displaying the 2 values as a 'consolidated note' on the browser with a delete button.
There can be any number of notes entered using this form.
How can I save the consolidated notes(i.e with Creator's name and the actual content of the note) in a string or array in the Local Storage and then retrieve it to be displayed on the browser when the browser reloads?
I understand that we save it using JSON.stringify and retrieve the data from the Local Storage using JSON.parse, but I'm unsure of how to save these multiple notes in the LOCAL Storage and retrieve them. Please help!
function addNoteLocalStorage(){
let notes = getNotesFromStorage();
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
obj.creator = creator;
obj.note = note;
let jsonstring = JSON.stringify(obj);
//create an array and push the string to the Object Array
objArray.push(jsonstring);
//store the new note
localStorage.setItem('notes', objArray);
}
The above code saves more than one note in the Local Storage.
Currently, this is how the array looks when stored in LS.
{"creator":"dgfdxsf","note":"dsgdsg"},{"creator":"sfs","note":"asd"}
How can I retrieve the values back into an object so that I can display each creator and note associated with that creator ?
Create an object of the values you get from the form.
var obj = {
creator : note
}
Now store this object in the local storage by stringifying in the same as you are doing (JSON.stringify). While retrieving, do a JSON.parse to retrieve the object.
If you have multiple objects like these, push them into an array and store that array in the local storage.
There is no need to convert a string to a JSON string, so you can play with your data without the need for stringify() and parse(). If you save the notes as array, however, you will need to do that.
// Add Note to Local Storage
function addNoteLocalStorage(){
//get saved notes. Set notes to empty string if it's the first time.
let notes = localStorage.getItem('notes') || '';
console.log("Notes return: "+notes);
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
let consolidatedNotesString = creator+":"+note;
//append the new note to the existing note
notes += '\n'+ consolidatedNotesString;
//store the new note
localStorage.setItem('notes', notes);
}
With your edited question, you're saving notes in the form of array of objects, in which case you will of course need to stringify and parse back the notes. One issue with your current code is that you're converting to string the objects(notes) but you save the array which contains the notes as it is. stringify the whole array instead and that's enough. And the way you access the stored notes is by the getItem method and parse it to get back the array. Make sure to save the empty objArray as notes in the local storage before calling addNoteLocalStorage function though, or you will need to check if notes are already in the storage before trying to parse it.
const objArray = [];
localStorage.setItem('notes', JSON.stringify(objArray));
function addNoteLocalStorage(){
objArray = JSON.parse(localStorage.getItem('notes'));
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
//push the string to the Object Array
objArray.push({creator, note});
//store the new note
localStorage.setItem('notes', JSON.stringify(objArray));
}
//And to get the first note and creator for example, you write like:
let noteArray = JSON.parse(localStorage.getItem('notes'));
let firstNoteCreator = noteArray[0].creator;
let firstNote = noteArray[0].note;

how to store and retrieve multidimensional array in local-storage JavaScript [duplicate]

This question already has answers here:
Storing array in localStorage with JSON in javascript
(2 answers)
Closed 3 years ago.
store data and retrieve multidimensional array in local storage java-script
Here I need to store array in local storage. and How do I retrieve?
As only strings can be assigned to localStorage, you have to convert the array to a string before assigning.
Convert the array into a JSON string using JSON.stringify() and using localStorage.setItem() store it in localStorage.
var num = [
['inp1','inp2'],
['inp3','inp4']
];
localStorage.setItem('arr',JSON.stringify(num));
With localStorage we are limited to store data as strings, therefore:
Use JSON.stringify to serialize the data to a string, before storing it in the local storage
const input = [[1], [2], [3]];
localStorage.setItem('myData', JSON.stringify(input));
Use JSON.parse to deserialize the data back to array when reading it form the local storage
const arr = JSON.parse(localStorage.getItem('myData'));
You may try like this:
var multidimensionarray = [
['1','2'],
['3','4']
];
localStorage.setItem('__array', JSON.stringify(multidimensionarray));
console.log(localStorage.getItem('__array'));
You can use JSON.stringify() and JSON.parse() combined with Window.localStorage methods setItem() and getItem():
To store:
localStorage.setItem('myItem', JSON.stringify(myMultidimensionalArray))
And to get the stored data with key myItem:
const array = JSON.parse(localStorage.getItem('myItem'))
Local storage is very simple data storage. It stores key (string) of which value is also (string and only string!). You need to use JSON.stringify(...) to store data and then parse it back JSON.parse(...)

Using localStorage/sessionStorage to store arrays

I am trying to save an array inside of a localStorage value. I can only access chars of the value, not the grouped value. I have been trying to write a function to group them by commas, but I can't figure out how to do it correctly.
// setting values
localStorage.setItem("foo", [15,"bye"]);
// writes the whole thing.
document.write(localStorage.getItem("foo")); // returns 15,bye
// only writes the first character, instead of one part of the array
// (in this case it would be 15).
document.write(localStorage.getItem("foo")[0]); // returns 1
I would use JSON.stringify to set the data and JSON.parse to fetch the stored data.
Try this:
localStorage.setItem("foo", JSON.stringify([15,"bye"]));
// writes the whole thing.
localStorage.getItem("foo"); // returns 15,bye
var data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])
localStorage can only store string in its value, that is why it is storing only 15;
Use JSON.stringify and store it in the local storage as localStorage.setItem("foo",JSON.stringify([15,"bye"]));
If you want to retrieve the value do as JSON.parse(localStorage.getItem("foo"));
You can parse json
let data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])
Or you can split by ',' and get the 0th index item.
localStorage.getItem('foo').split(',')[0]

Can a localStorage value be an object or array?

I am trying to set storage in the user's computer with localStorage("save","{teams:5, points:20}, etc. But I'm not sure if the value can be an object. I've checked the internet, but I can't seem to find clear answers there.
var data={
teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage ("save", data);
Thoughts?
No, the key and value must be a DOMString. See https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem
What you can do is serialise your data as JSON before setting it
localStorage.setItem('save', JSON.stringify(data))
When reading the value, you can parse it back into an object
let saveData = JSON.parse(localStorage.getItem('save'))
local storage limited to handle only string key/value pairs you can do like below using JSON.stringify and while getting value JSON.parse
var testObject = { {name:"test", time:"Date 2017-02-03T08:38:04.449Z"} };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
No, localstorage takes string as and saves it. If you want to save any object then convert it on string and then save it.
while fetching it from local storage you we get string. you may easily covert it into object.
if you directly save an object into localStorage then it will be saved in such manner "[object Object]" and while fetching it from localStorage, you will get "[object Object]" as String.
Wrong Code:
var data={teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage.setItem("save", data);
localStorage.getItem("save")
you will get "[object Object]"
Right Code:
var data={teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage.setItem("save",JSON.stringify(data));
localStorage.getItem("save")
While fetching value from localStorage
Wrong Code:
localStorage.getItem("save")
It will fetch data in form of string.
Right Code:
JSON.parse(localStorage.getItem("save"))
It will return data in form of object.
I hope the solution is well explained.
No, It can't be but you can use stringify. For example:
localStorage.setItem('user', JSON.stringify(r.user));
You need to use the localStorage.setItem(keyName, keyValue);
For Storing a Object, you can make use of JSON.stringify(object) which converts the object to a string.
From MDN
keyName
A DOMString containing the name of the key you want to
create/update.
keyValue
A DOMString containing the value you want to
give the key you are creating/updating.

How to access values from keys from Local Storage in AngularJs?

I want to access the values from some keys in my Local Storage in the most easiest way with AngularJs.
In Resources --> Local Storage I have:
Key:myKey
Value:{ "layouts":[ other_things ],"states":{ other_things },"storageHash":"fs4df4d51"}
I tried:
console.log($window.localStorage.key(0).valueOf('layouts'));
//or
console.log($window.localStorage.getItem('myKey'));
RESULT
myKey
You can do:
$window.localStorage['myKey']
If the data is of stringified(read: JSON.stringify) then:
angular.fromJson($window.localStorage['myKey']);
LocalStorage stores values in strings, not objects. You will need to serialize your object before assigning it and deserialize it when fetching.
var myObject= { "layouts":[ other_things ],"states":{ other_things },"storageHash":"fs4df4d51"};
// Stringify JSON object before storing
localStorage.setItem('myKey', JSON.stringify(myObject));
// Retrieve the object
var myRetrievedObject = JSON.parse(localStorage.getItem('testObject'));
From local storage you get JSON data, so you need to parse it to JS object,
JSON.parse($window.localStorage.myKey).layouts

Categories

Resources